- Home /
Variables keep getting swapped with the other.
I have two TMPro's in my scene and my goal with them is to display variables gotten from objects that get caught within a raycast projected based on the Cursor's position.
The problem I keep having is upon running the script and getting the variable info from an object, one of the public TMPro variable gets switched out to the other one, while the second one stays the same.
Here is the code:
using UnityEngine;
using TMPro;
public class raycastGetVariables : MonoBehaviour
{
public TextMeshPro healthText;
public TextMeshPro nameText;
public float damage = 0f;
public Camera cam; // Get a public reference to the camera.
private void Update()
{
healthText = FindObjectOfType<TextMeshPro>(); // Finds TMPro object in scene.
nameText = FindObjectOfType<TextMeshPro>();
Ray ray = cam.ScreenPointToRay(Input.mousePosition); // Allows the ray to be projected from the camera and it's position to be the mouse's position.
RaycastHit hitResult; // Store the hit result.
if (Input.GetButtonDown("Fire1")) // Fire1 is mapped to the left mouse button.
{
print("CLICK!"); // To ensure that the click registered. Gotta be sure.
if (Physics.Raycast(ray, out hitResult)) // Checks if the raycast hit something.
{
if (hitResult.transform.gameObject.tag == "Enemy") // Will check if the collider has the tag "Enemy".
{
var target = hitResult.transform.gameObject; // Store the hit result transform and GameObject to a variable.
variableContainer container = target.GetComponent<variableContainer>(); // Gets the script component in which the variables are stored.
string nameVar = container.Name; // Store name var into a string var.
float healthVar = container.Health; // Store health var into a foat var.
nameText.text = "Name: " + nameVar; // Update the nameText to display the name.
healthText.text = "Health: " + healthVar.ToString(); // Update the healthText to display the health, and converted the float to string.
}
}
}
}
}
I believe it has something to do with FindObjectOfType, but I don't know what. Is there an alternate way to do this? or a more efficient way of doing this? If there is a way to fix it, please tell me. Thank You! I should add that I am a noobie to unity, so I understand if one finds the code atrocious.
Answer by Namey5 · Jul 17, 2020 at 07:27 AM
Remove the lines that assign to the healthText and nameText variables and assign them manually in the inspector. FindObjectOfType will just return the first object it finds - you use it twice (both times it will find the same component as nothing has changed in the scene) and thus assign the same object to both variables.