- Home /
Question by
Nakemar · Mar 19, 2017 at 08:25 AM ·
instantiateprefabsinstanceprefab-instance
How can you make a Instanciate prefab follow a scene object?
Hello im new to Unity and im trying to make a scene in which if you activate a trigger a Ghost will appear and start to follow the player
this is the code i have in a box that when the player touches it the trigger will activate
public Transform Spawn;
public GameObject Ghost;
public GameObject Player;
public int speed;
public bool Ismoving = false;
void OnTriggerEnter()
{
Ismoving = true;
Instantiate(Ghost,Spawn.position,Spawn.rotation);
}
void Update()
{
if (Ismoving == true)
{
Vector3 localPosition = Player.transform.position - transform.position;
localPosition = localPosition.normalized;
transform.Translate(localPosition.x * Time.deltaTime * speed, localPosition.y * Time.deltaTime * speed, localPosition.z * Time.deltaTime * speed);
}
}
Ghost is a obj which i made into a prefab. Spawn is a Null Object that is a child of the box, its just there to set the coordinates.
I tried to set the code in Update to the prefab but i cant reference the player because is in the scene
right now only the box follows me not the ghost Thanks for the help im really new to Unity
Comment
Best Answer
Answer by Hellium · Mar 19, 2017 at 08:26 AM
What you have to do is attaching a script to the ghost to make him follow the player.
// Your initial script
public Transform Spawn;
public Ghost GhostPrefab; // Drag & Drop the prefab with the Ghost script attached to it
public GameObject Player;
public int speed;
void OnTriggerEnter()
{
(Instantiate(GhostPrefab,Spawn.position,Spawn.rotation)).SetTarget( Player, speed ) ;
}
// The script to attach to the Ghost prefab
public class Ghost : MonoBehaviour
{
private Transform target = null ;
private float speed = 0 ;
void Update()
{
if( target != null )
transform.Translate((target.position - transform.position).normalized * speed * Time.deltaTime ) ;
}
public void SetTarget(GameObject newTarget, float chaseSpeed )
{
target = newTarget.transform;
speed = chaseSpeed;
}
}