Reputation: 3
I have 9 3d cubes. each cube has a script component, checking if the cube was touched. if so, it logs the name of the touched cube.
want: the name of the cube is logged once. reality: the name of the cube is logged 9 times (once for every cube) which makes sense .. its the same script attached to all 9 cubes. see the script below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class main: MonoBehaviour
{
public string touchedObjectsName;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
{
Ray raycast = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit raycastHit;
if (Physics.Raycast(raycast, out raycastHit))
{
touchedObjectsName = raycastHit.collider.gameObject.name;
Debug.Log(touchedObjectsName);
}
}
}
}
question: is it possible to modify the above script to log only once even if it is attached to several game objects?
thanks, dear community!
Upvotes: 0
Views: 729
Reputation: 90600
Well as you say yourself: Your script is running on all 9 cubes!
So 9 times you make a Raycast, 9 times you hit always the same object and print its name 9 times.
You could of course simply check if you hit yourself:
if (Physics.Raycast(raycast, out raycastHit))
{
// only do it if the hit object is the same as this script is attached to
if(raycastHit.gameObject == gameObject)
{
touchedObjectsName = raycastHit.collider.gameObject.name;
Debug.Log(touchedObjectsName);
}
}
But that's very redundant => unefficient!
Rather only have this script running somewhere in your scene once as it can already track any touched object so there is no need to run it multiple times.
Upvotes: 1