- Home /
This only works for 1 object!
Following script is attached to every gameObject in scene that i would like to interact with. When I look at one cube code is working, and when looking at the other one, it does ABSOLUTLY NOTHING! what have I done wrong? (I did not forget to attach the script to both gameobjects...)
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class CheckIfInteractable : MonoBehaviour {
public float interactionDistance = 2f;
Text descriptionText;
void Awake()
{
descriptionText = GameObject.Find ("DescriptionText").GetComponent<Text> ();
}
void Update()
{
if (Check (GetComponent<Collider>(),interactionDistance))
{
descriptionText.text = gameObject.name;
}
else
{
descriptionText.text = null;
}
}
private bool Check (Collider col, float interactionDistance)
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = Camera.main.ScreenPointToRay (new Vector3 (x, y));
RaycastHit hit;
if (col.Raycast (ray, out hit, interactionDistance))
return true;
return false;
}
}
Answer by jdean300 · Feb 13, 2017 at 04:37 AM
The problem is that Cube 1 is setting the descriptionText to null every frame and overwriting any updates the other cubes make to the text. This simple fix should work:
bool wasShown = false;
void Update()
{
if (Check (GetComponent<Collider>(),interactionDistance))
{
descriptionText.text = gameObject.name;
wasShown = true;
}
else if (wasShown == true)
{
wasShown = false;
descriptionText.text = null;
}
}
Your answer
Follow this Question
Related Questions
Check if collider is colliding with anything non specific? 1 Answer
checking colliders from multiple raycast 1 Answer
Problems with the triggers(not recognized) 1 Answer
How can I add the OnTriggerEnter function to all game objects that I instantiate? 1 Answer
Check if trigger collider is touching other trigger collider 2 Answers