Search Unity

Resolved How to use transform.LookAt() on a newly-instantiated object?

Discussion in 'Prefabs' started by Deleted User, Mar 7, 2021.

  1. Deleted User

    Deleted User

    Guest

    Sorry for not posting any code (I'm not at my computer), but I currently have a script which takes a 3D arrow model and makes it always point towards a moving spaceship, upon the spaceship's destruction, a SpaceshipSpawner object will spawn a new spaceship and the arrow will correctly point towards the new spaceship.

    Yes, everything works, however, the Unity error is still throwing up missing reference errors. I want to get rid of the editor issues since I'm worried that they might cause issues down the line.

    Is there a simple way for me to make my arrow point towards a newly-instantiated spaceship without the editor yelling at me?

    My current attempt is assigning the instantiation as a variable, then referencing that variable in the arrow script and passing the position of the the instantiation variable to my LookAt() function.

    I'm still quite new to Unity and C# so I may be missing something obvious but I'd appreciate the help.
     
  2. Deleted User

    Deleted User

    Guest

    I found a way to do it, essentially it is possible to just tag your prefab and then by using FindGameObjectsWithTag("YourTagHere"), you can just assign a variable to it and pass it into the LookAt() function (remember to assign an index).

    Here is an example with my code:
    Code (CSharp):
    1. void Update()
    2.     {
    3.         GameObject[] targetList = GameObject.FindGameObjectsWithTag("Pacemaker"); //should only have 1 at any given time
    4.         transform.LookAt(targetList[0].transform);
    5.     }
    To clear up any possible confusion, the pacemaker is the name of an enemy in my game, there is only ever one in-game at any time, for that reason, I am looking for targetList[0] (indicating that I'm looking for the first item in targetList.

    Any problems, let me know and I'll try and explain my code for you!