- Home /
How to Reference Player when Instantiating Prefab
Hello, I have created a car by using the default Unity Al with my own police car model on top. I have made a prefab of this car and I am trying to instantiate it into my scene. The instantiation works, but the problem occurs when I try to make it follow my player. The car just stays in one spot and does nothing. I have looked in the Inspector and when a new vehicle is instantiated, it has no references to my player. I understand prefabs cannot keep references to objects in a scene but is there another way around this? If there is a way, could somebody explain this to me. as I am new to Unity and know only the basics. Thank you.
Answer by Mouton · Sep 26, 2019 at 04:42 PM
You need to add a reference to the Player in a script of your freshly instantiated GameObject. You can do it from the instantiator script or from the instanciated one.
From the instatiator class
using UnityEngine;
class ClassWhichInstantiatePrefab : MonoBehaviour
{
public GameObject Prefab;
private Player _player;
private void Start()
{
// You may need a different logic here to retrieve
// the Player, change it to fit your needs.
_player = GetComponent<Player>();
}
public void MethodWhichInstantiatePrefab()
{
var go = Instantiate(Prefab);
var component = go.GetComponent<YourComponent>();
component.Player = _player;
}
}
From the instance class
class MyClass
{
private Player _player;
private void Start()
{
_player = FindObjectOfType<Player>();
}
}
Thanks for the reply @$$anonymous$$outon , I have a problem when I put the first script into $$anonymous$$icrosoft Visual Studio, a few things are underlined in red and I am not sure how to fix it. This is a screenshot of the script:
You need to import UnityEngine. Your class needs to inherit from $$anonymous$$onoBehaviour
too.
Add using UnityEngine;
on the first line of your script:
using UnityEngine;
class Player : $$anonymous$$onoBehaviour
{
...
Sorry again @$$anonymous$$outon , there is one other spot near the end of the script that still has an error,