- Home /
referencing a component of a gameobject
i have looked and have been unable to find the solution to my current problem or if i found it i didn't understand it. basically i am trying to call up the State of a gameobject called hinge in the hierarchy. instead what i get is "null" what am i doing wrong?
#pragma strict
var Chest : GameObject;
private var chestState : Component;
function Start ()
{
Chest = GameObject.Find("Hinge");
chestState = Chest.GetComponent("State");
print(Chest);
print(chestState);
}
function Update ()
{
Debug.Log(chestState);
}
function Raise()
{
if(chestState == "open")
{
animation.Play("Raise");
}
}
state refers to a section of script on the other object
public enum State
{
open,
close,
inbetween
}
Ins$$anonymous$$d I get is "null"
What is that supposed to mean? Are you getting a NullReferenceException
? If so, what line?
@$$anonymous$$ I think it's pretty obvious that State
is an enum
, as posted in the question.
when i run it the debug comes out with
Null UnityEngine.Debug:Log(Object) Tablet:Update() (at Assets/Tablet.js:16)
I think this will help you:
chestState = Chest.GetComponent("State") as State;
Oh sorry this is c#.
that got me this
Assets/Tablet.js(16,53): BCE0018: The name 'State' does not denote a valid type ('not found'). Did you mean 'UnityEditorInternal.State'?
Answer by Jeff-Kesselman · May 11, 2014 at 02:46 PM
State is an enum, not a class.
You need to get the Class Instance/Script State is part of, that is the component.
Then you can address things on that class instance like any other object.
Additionally, I don't know Unityscript well but it seems to me that State is an Enum definition and not a field, I don't think you can use it the way you are trying to anyway...
Done right, in C# it would look something like this:
File StateHolder.cs:
public class StateHolder:MonoBehaviour {
public enum State
{
open,
close,
inbetween
}
public State myState = State.open;
... etc
}
File StateGetter.cs
public class StateGetter:MonoBehaviour {
void Start() {
Chest = GameObject.Find("Hinge");
StateHolder chestState = Chest.GetComponent<StateHolder>();
print(Chest);
print(chestState.myState);
}
}