Make an instantiate object with specific variable value

Hi, I have this code :

var instance : GameObject = Instantiate(neutral, Vector3(Random.Range(-4.0, 16.0),0,Random.Range(0.0, 11.0)), Quaternion.Euler(-90,180,0)); = "neutralC";

I need to modify a variable ( life ) and attribute a value to the instance. How can I do that ?

The simplest method is to make life public and do the following (c#). Get component needs to know the type of component you are accessing. The component must be a monobehavior.

// Used in the method to set the variable
instance.GetComponent<Life>().life = 50;

// The component script
public class Life : MonoBehaviour {
    public float life = 0;

You will need to adjust this code to call the correct name of your component. You will also need to convert it to JavaScript, the syntax is slightly different.

You can also investigate using a factory pattern, however that’s probably overkill for your situation.

If you mean accessing a script which is on the Instantiated prefab. Then use:


If by life you mean Health then it’s most likely a int so if you wanted to add 10 health to the object do :

    instance.GetComponent(SCRIPTNAME).The-Variable += 10;

Hope this helped