I am fairly new to Unity and am currently working on a small project.
My problem is this.
I want to display text when I click on the cube.
I have a total of four different cubes, all of which should display different text when clicked.
The solution I have so far works, but of course now when I click on the cubes the same text comes up and if I assign each cube its own text they all appear at once.
The cubes should also rotate and when clicked on just stop and display the text.
I tried it with the Event Trigger System and assign different texts, but without success.
Any suggestion for a solution?
I tried it with the Event Trigger System and assign different texts, but without success.
Any suggestion for a solution?
Updating TextMeshPro dynamically
If you're looking only to change one TextMeshPro
component but vary the text per cube, then you could add a custom string
per GameObject
:
[SerializeField] private string customText = "Default Text - Change Me!";
And update the text inside the OnMouseDown()
method:
textMeshProUGUI.text = customText;
Although with the latter, the _isRevealed
state would still be per cube, meaning that toggling the state of one will make the text disappear, even if others are active.
CodePudding user response:
You are using input.GetMouseButtonDown, when you click anywhere all the boxes run the same code, you don't specify which box is clicked you only looking for a click, I suggest you use raycast to send a ray to detect which box you are clicking and run ,
Add this script to the camera or player and give all the boxes gameobject a "Box" Tag :
void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { Transform objectHit = hit.transform; if (objectHit.CompareTag("Box")) { objectHit.GetComponent<Rotator>().RotateObject(); } } } }
add this function to the Rotator Script and remove the code from update :
public void RotateObject() { if (rotateObject) { rotateObject = false; Text.SetActive(true); } else { rotateObject = true; Text.SetActive(false); } } }