- Home /
Syntax troubles (GetComponent and changing variables)
Hello. It seems a lot of other people have trouble accessing and changing variables in other scripts/components however I've managed to make myself a problem that the other answers I've read weren't about to address.
I have a bool I want to change that lies on a different script. Both the script making the change and the script containing the changing variable lie on the same gameObject.
Can someone point out what I'm doing wrong? I'm working in C#
var go = this.gameObject;
go.GetComponent("PlayerStateSync").moving = false;
That tells me UnityEngine.Component doesn't contain a definition for the "moving" bool I'm trying to reference.
var go = this.gameObject;
var com = go.GetComponent("PlayerStateSync");
go.com.working = false:
That tells me UnityEngine.GameObject can't find a definition for the bool.
Answer by hiddenspring81 · May 29, 2013 at 06:04 PM
Try this instead
var go = this.gameObject;
var com = go.GetComponent<PlayerStateSync>();
com.working = false;
Or if you want to be really fancy
GetComponent<PlayerStateSync>().working = false;
This assumes that PlayerStateSync
is a subclass of MonoBehaviour
.
What? Really?
Why does that work? It looks almost exactly the same as my attempt!
There are three different version of GetComponent(). The version that you've used GetComponent("PlayerStateSync")
will return an object of type Component
, which you'd then have to cast into an instance of PlayerStateSync
,
var com = GetComponent("PlayerStateSync") as PlayerStateSync;
If you want to avoid having to perform the casting operation, then you can use the generic version of GetComponent()
var com = go.GetComponent<PlayerStateSync>();
These two version are identical, it's just that the second option is a bit cleaner and more readable.
Ahhhh ok. Yes I see it in the documentation now that you've explained it.
function GetComponent. () : T function GetComponent (type : String) : Component
It's not apparent to me what those mean so I've just been glossing over it <- noob.
So now I can better read an API reference, thanks!
Your answer
Follow this Question
Related Questions
Using a variable value with GetComponent 1 Answer
fix script to get C# var from another object instead of object this script is attached to 2 Answers
C# Access to a variable by another script attached in a gameObject in the scene. 2 Answers
Calling variable accross scripts in C# problem (Closed) 1 Answer
Getting a Variable on Script B to equal a variable from script A 0 Answers