Reputation: 41
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
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
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