I know this is one of those questions that pops up a lot. I read through the forums a bit before posting but I couldn’t find an answer.
I’m trying to access a variable in another script on an instantiated object.
Script A has this Component
var MySpeed = GetComponent("Personal Stats").SpeedStat;
Script B (Personal Stats) is being accessed and is on the same object. However, I keep getting the error that it’s not accessing an instance of the object.
Script A and B are both instantiated scripts. Meaning, there are multiple objects running these same scripts but in different ways. I need Script A to access the Script B on the same exact object, rather than one of the object scripted objects.
How can I accomplish this? Also, I can’t use the “FindWithTag” option.
Hope I explained that well enough.
One last thing, this is sort of a miscellaneous question, but what is the difference between a gameObject and a GameObject?
Is the script named “Personal Stats” with the space? I didn’t know you could do that. Maybe try renaming it to one without the space (e.g., “PersonalStats.js”)?
I have, in the past, tried to do this, and FizixMan is right, you cant have spaces in the names of your scripts, just like your variables and functions.
There are a few things which are insanely crazy stupid.
To answer your question, GameObject is a script which represents any physical object in your scene. Unity - Scripting API: GameObject It’s a “type” (just how int, string, Vector3, Transform, MeshRenderer are types)
gameObject on the other hand is a property of any Transform instance which provides you a reference to an instance of that GameObject type/script. Unity - Scripting API: Component.gameObject
So if you only have a reference to the “transform” of an object (which is what you get sometimes for some physics stuff) you can still crawl back to the encompassing GameObject instance for that physical object in your scene.
EDIT: oh yeah, for JavaScript, the generics code is:
var myScriptA = GetComponent.();
This is the preferred way of using the GetComponent method. It forces type-safety and will catch errors when you compile (rather than when you try to run the game).