- Home /
 
Problem setting different targets for the player.
I'm building a game where the player interacts with world objects and stuff like that. I have created the scripts below: one for the object (Interaction) and the other for the Player (MoveToInteract). The problem is that when i have more than one objects, the player target always changes to one of them and not the others. Any suggestions?
Interaction.cs
 public class Interaction : MonoBehaviour {
     public Renderer rend;
     public bool interactable = false;
     public GameObject player;
 
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
         if (interactable)
         {
             player.GetComponent<MoveToInteract>().interactable_target = gameObject;
         }
         else
         {
             player.GetComponent<MoveToInteract>().interactable_target = null;
         }
     }
 
     private void OnMouseEnter()
     {
         rend.material.color = Color.green;
         interactable = true;
     }
 
     private void OnMouseExit()
     {
         rend.material.color = Color.white;
         interactable = false;
     }
 }
 
               MoveToInteract.cs
 public class MoveToInteract : MonoBehaviour {
     public GameObject interactable_target;
 
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
         
     }
 }
 
              Answer by tormentoarmagedoom · Aug 08, 2018 at 12:49 PM
Good day.
If i undersrand what ylu explain, this code is wrong...
Look... If you have only one object. Every frame this object sends to the player script one of this things:
Target =the object
Or
Target = null.
If you have 2 objects , during the update each object will change that player variable to one of the results.
This means every at the ens of each frame the player will have one value in the target variable, but "he doesnt know" if there are more than 1 object, or if the last object to execute its update() turns target variable to null, the player will finish the frame with a null, maybe there are some objects interactable, but lastone wasnt so the variable is null.
You need to create a system for example where objects informs player thay are there, and is the player who decise the final target.
Bye!
I just found a solution. It is way more simple than creating a whole system. I just moved the GetComponent functions in the Interaction script from the Update method to the On$$anonymous$$ouseEnter and On$$anonymous$$ouseExit methods. Now it works perfectly!
Your answer
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Enemy AI Movement To A Target(Player) In A 2D Game 3 Answers