LookAt method not working on instantiated objects.
Hello all. I am new to game development, and have been playing around with some concepts I've learned so far. I am having an issue instantiating a prefab that has a transform.Lookat() method. When I manually place one of these prefabs, it performs as intended, following my target, but when I instantiate them at runtime they don't follow the target. The rest of the script works (they also instantiate projectiles and propel them forward), just not the LoookAt() method. Do I not understand how this method works?
Here are the pertinent bits:
void Update () {
time += Time.deltaTime;
transform.LookAt(target.transform);
if(time > 2.0) {
time = 0;
GameObject p = (GameObject)Instantiate(projectile, transform.position, Quaternion.identity);
p.GetComponent<Rigidbody>().AddForce(transform.forward * force);
Destroy(p, 3);
}
}
This controls the launcher object, which creates a projectile and fires it at the target.
void nextLevel() {
Vector3 randV31 = new Vector3(Random.Range(-35.0f, 35.0f), 1.50f, Random.Range(-35.0f, 35.0f));
Vector3 randV35 = new Vector3(Random.Range(-35.0f, 35.0f), 1.50f, Random.Range(-35.0f, 35.0f));
transform.position = GameObject.Find("start").transform.position;
Instantiate(scoreSphere, randV31, Quaternion.identity);
Instantiate(launcher, randV35, Quaternion.identity);
}
This bit of script is attached to the player and when a certain condition is met, it instantiates the launcher object, which is the prefab in question. Any help you could provide would be very appreciated.
Answer by RickshawDerpyDerp · Dec 13, 2019 at 04:30 PM
Greetings from the future, @Goreleth! I don't think you are providing enough information because you never show us how you are assigning the target. However, others (myself included) recently had this same problem and it is likely that the instantiated object's name is not what you think it is going to be. For example, if you have a prefab whose name is "MyPrefab", than the first instance of this object that Unity creates with Instantiate()
is called "MyPrefab (Copy)". So using target = GameObject.Find("MyPrefab").transform;
fails. It is possible that target = GameObject.Find("MyPrefab (Copy)").transform;
could succeed (unverified) but I opted to use target = GameObject.FindGameObjectWithTag("Player").transform;
instead. For more complicated scenes, you may need to use other methods, such as searching the contents of containers.
Your answer
Follow this Question
Related Questions
Unity gets hang and nothing work in it, even I have to close it from the task manager 0 Answers
How do I Instantiate a prefab at the x axis position of where the UI button was clicked 1 Answer
Want to instantiate Prefab in its parent. 1 Answer
Logic behind multiple copies of a prefab? 2 Answers
My code is instantiating many prefabs, i only want one. 1 Answer