Store script from GetComponent ?

Hi All,

Trying to figure out how to store a script from GetComponent.

For example:

private gameobject storeHere;

void Start ()
{
storeHere: gameObject.GetComponent<ThisComponent>();
}

But this doesn’t work, because it’s not a gameobject obviously… it’s a script…But what can I store a script in ?

Cheers !

Question is not clear. Do you want to get a script from a game object or add and get the script from the game object cause you have declared gameobject private. and you should use private GameObject storeHere;.

–

@AdhamT No, I had player and spawnPoint both assigned.

–

1 Answer

1

If you want to store a variable of the type ThisComponent, the variable needs the type ThisComponent:

private ThisComponent storeHere;

void Start() {
    storeHere = GetComponent<ThisComponent>();
}

Note that gameObject.GetComponent is not neccessary, it does the same thing as just GetComponent.

If by ThisComponent you mean the current MonoBehaviour, you don’t need to store it, ever, as it’s available through the keyword ‘this’.

If you want to store reference to a script, but don’t know the exact type of the script, you’re looking for the class MonoBehaviour, as that’s what all of the scripts that you can attach to GameObjects inherit from. So that’d be:

private MonoBehaviour storeHere;

Though that’s unlikely, as you won’t have access to any of the methods or variables defined in the script.

I think in JS you need a dot after GetComponent. storeHere = GetComponent.<ThisComponent>();

–

This worked like a charm ! Thanks a lot for your help and explanations. Very clear and extremely helpful.

–