Referencing in a prefab


Following Scenario:
I’ve got a player and another game object, which is instantiated.
Now I’m trying to get the references onto that object.
I’ve messed around a bit, but nothing works.
This is the script I’ve ended up with, but Unity tells me “Type mismatch”

tonFab.GetComponent().collect = this.gameObject.GetComponent();

tonFab is the object I’m instantiating
StatusTon is the Script attached to the instantiated object
collect is the reference I’m trying to set
Collect is the script attached to my player

What am I doing wrong or what is the right way?

Thanks in advance


Hi Pyppo,

I’m not exactly sure what you want to achieve, but I think the problem is that you don’t specify the type of component you are trying to get from the game object. You need to do that either by generics or by typeof() operator (I prefer generics):

StatusTon statusTon = tonFab.GetComponent<StatusTon>(); // store StatusTon component in local variable
if (statusTon != null) { // make sure tonFab actually had a StatusTon script on it
    Collect collectScript = GetComponent<Collect>(); // get the Collect script, check it the same way; you don't need to use 'this', nor 'gameObject', because it is NOT ambiguous on what you want to call GetComponent()
    if (collectScript != null) {
        statusTon.collect = collectScript;