VincentTheonardo
VincentTheonardo

Reputation: 331

Unity3d transform.position not returning the correct value

A little background on what I'm working on : Basically I have a cube model which will be used to generate some terrain structure. All of those gameobjects were created on Runtime by doing :

float yPos = 0f;
 float scale = 0.5f;
 var robot = GameObject.Instantiate(grassTile) as GameObject;
 robot.transform.position = new Vector3(0, yPos, 0);
 robot.transform.localScale = new Vector3(scale, scale, scale);
 robot.transform.rotation = Quaternion.Euler(-90, 0, 0);

 width = robot.GetComponent<Renderer>().bounds.size.z;
 for(int i=0;i<5;i++){
     yPos += width;
     robot = GameObject.Instantiate(grassTile) as GameObject;
     robot.transform.position = new Vector3(0, yPos, 0);
     robot.transform.localScale = new Vector3(scale, scale, scale);
     robot.transform.rotation = Quaternion.Euler(-90, 0, 0);
     //attach the script
     robot.AddComponent<CubeBehavior>();
 }

What's inside the CubeBehavior.cs :

void Start () {
     }

     // Update is called once per frame
 void Update () {
         if (Input.touchCount > 0) {
             Debug.Log(transform.position);
         }
 }

What happened is no matter which cube I touch, it will always return the last cube position. Please enlighten me about this problems. Thanks in advance

Upvotes: 0

Views: 505

Answers (1)

Basile Perrenoud
Basile Perrenoud

Reputation: 4110

You have no code that detect which cube was touched.

Input.touches just tells you how many touches are currently detected on the screen.

To detect touches, you will need to do some more work. One of the possible solution is to implement touch event handlers. Example inspired from the doc:

public class CubeBehaviour : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    //Detect current clicks on the GameObject (the one with the script attached)
    public void OnPointerDown(PointerEventData pointerEventData)
    {
        //Output the name of the GameObject that is being clicked
        Debug.Log(name + " click down at position " + transform.position);
    }

    //Detect if clicks are no longer registering
    public void OnPointerUp(PointerEventData pointerEventData)
    {
        Debug.Log(name + "No longer being clicked");
    }
}

This will need an EventSystem somewhere in your scene. Potentially, you will also need trigger colliders on the cubes, not sure

Upvotes: 2

Related Questions