1

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.

0

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.