Vitor Speranza
Vitor Speranza

Reputation: 41

Unity C# store script in variable

I can store a GameObject within a variable with something like:

GameObject Target = SomeGameobject; 

How do i do that for a script?

SomeVariableDefinition TargetStatus = Target.GetComponent<Status>();

What is the variable? Is there such a thing?

Thanks in advance, Sorry for the bad english.

Upvotes: 1

Views: 10178

Answers (2)

Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10551

Just like to store a game-object, you can also save any script.

GameObject Target = SomeGameobject; //Gameobject sotre

You need to remeber always that game-object is also a script.

Status TargetStatus = Target.GetComponent<Status>();//Status script ref store in TargetStatus Variable

Variable type should need to be compatible with assigned object type(in our case script name)

Upvotes: 1

Programmer
Programmer

Reputation: 125275

I assume you are asking how to get a reference of a script that is attached to another GameObject.

You are almost correct. The type on the left and the type in the GetComponent must match.

SomeVariableDefinition TargetStatus = Target.GetComponent<SomeVariableDefinition>();

OR

Status TargetStatus = Target.GetComponent<Status>();

Understand that if the Target GameObject does not have that script you want to access, it will return null.

Below is full Example of how to access Another script instance, variable or function from another script.

public class ScriptA : MonoBehaviour{

    public int playerScore = 0;

    void Start()
    {

    }

    public void doSomething()
    {

    }
}

Now, you can access variable playerScore in ScriptA from ScriptB.

public class ScriptB : MonoBehaviour{

    ScriptA scriptInstance = null;  

    void Start()
    {
      GameObject tempObj = GameObject.Find("NameOfGameObjectScriptAIsAttachedTo");
      scriptInstance = tempObj.GetComponent<ScriptA>();

      //Access playerScore variable from ScriptA
      scriptInstance.playerScore = 5;

     //Call doSomething() function from ScriptA
      scriptInstance.doSomething();
    }
}

Upvotes: 0

Related Questions