Find is not allowed in Update yet I need to get a position of another component once every 0.35f seconds
Hello. I know Unity doesn't let the Find function in Update function, but rather in Start. But I need to get a position of a component that my current script is NOT on. A part of my Update code:
 void Update()
     {
         timer += Time.deltaTime;
         if (timer >= 0.35f) 
         {
             newPlayerLength = GameObject.Find("Player_Dragon").GetComponent<Player_Movement>().lengthOfPlayer;
 
             newPlayerPosition = GameObject.Find("Player_Dragon").GetComponent<Player_Movement>().transform.position;
 
             timer = 0f;
         }
 }
How can I get the new player length and position without using the Find function?
Answer by Hellium · Nov 22, 2018 at 03:12 PM
I don't where you have read that Unity doesn't let the Find function in Update function. YOU CAN, but it's not advised since the function is heavy.
 // Drag & drop the gameObject with the player movement in the inspector
 [SerializeField]
 private Player_Movement playerMovement;
 // The following getter will try to retrieve it at runtime
 private Player_Movement PlayerMovement
 {
     get
     {
         if( playerMovement == null )
         {
             GameObject playerDragon = GameObject.Find("Player_Dragon") ;
             if( playerDragon != null )
                 playerMovement = playerDragon.GetComponent<Player_Movement>() ;
             else
                 Debug.LogError("Can't find Player_Dragon object. Is it enabled ?" );
         }
         return playerMovement;
     }
 }
 
 void Update()
 {
     timer += Time.deltaTime;
     if (timer >= 0.35f && PlayerMovement != null ) 
     {
         newPlayerLength = PlayerMovement.lengthOfPlayer;
         newPlayerPosition = PlayerMovement.transform.position;
 
         timer = 0f;
     }
 }
Sorry, how to drag the game object? The script where I need the length and position is a prefab named Dragon_Pieces and the game object with the length and position script is called Player_Dragon, obviously. Do I need to drag the Player_Dragon in the Dragon_Pieces inspector? Because I cannot do that.
Everything should be fine with the given script. If you can't drag & drop, the getter will retrieve the object at runtime. If Dragon_Pieces is instantiated after Dragon_Player is in the scene, Find should be called only once. 
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                