John
John

Reputation: 151

Unity3D optimize code

I have 2 objects that do the same thing in terms of the behavior but the only thing that differs is the damage dealt. Right now i have 2 scripts that are a copy paste from each other. Same functions same everything. How can i make 1 script to optimize my work and not duplicate my stuff? Thanks.

using UnityEngine;
using System.Collections;


 public class Script1 : MonoBehaviour {

private float attackDamage = 5;

void OnCollisionEnter (Collision item) { item.gameObject.GetComponent().Damage(attackDamage); disableObs(); }

public void disableObs()
{
    gameObject.SetActive(false);
}

}

Script 2 is the same thing. I just change the damage variable

Upvotes: 2

Views: 284

Answers (2)

Everts
Everts

Reputation: 10701

Decorate your variable with:

 [SerializeField] private int damage;

Now this is a private variable with exposure in the Inspector.

Concerning the workflow, you can drag as many of Script1 onto many objects, they will have their own Script1 set of actions. But the purpose is that you can have infantry with damage value as 1 and tank with damage as 100. All you need to do is set the value for the prefab. One place to set them all. Then you can instantiate the prefabs and they will use the given values.

Upvotes: 1

João Martins
João Martins

Reputation: 332

You can change the damage variable to public and when you add the script to different objects set that variable via inspector. Or if you are doing that change by code on instantiation just call the setDamage(damage) function to the specific object:

gameobject.GetComponent<Script1>().setDamage(damage1);
gameobject2.GetComponent<Script1>().setDamage(damage2);

Upvotes: 1

Related Questions