Why does my object instantiation work, but return null? [closed]

Why does my object instantiation work, but return null? [closed]






Closed. This question is off-topic. It is not currently accepting answers.
                            
                        










Want to improve this question? Update the question so it's on-topic for Game Development Stack Exchange.
                        
Closed 5 years ago.



For some reason, the LogError runs:
Player clone = Instantiate(player, this.transform.position,
    Quaternion.identity) as Player;

if(!clone) { Debug.LogError("WTF"); }
else       { Debug.Log("WE GOT IT"); }

My object appears, but if I try to do anything with it afterwards  its value is null, and the if(!clone) triggers.
Why is this happening?
The player is a gameobject and is assigned (its my player prefab) and Player is what my prefab is called. I also have a Player.cs script. Is Unity confusing my prefab and script or something?

Solutions/Answers:

Answer 1:

The Instantiate function returns an abstract Object reference, that’s why it effectively instantiates the object but it is also gives you a type error.

What you need to do, in order to access your Player script, is something similar to the following

GameObject obj;
obj = Instantiate(playerPrefab, Vector3.zero, Quaternion.identity) as GameObject;
Player player = obj.GetComponent<Player>();

And that’s it.

References