Issue with transform.position and duplicating an object.

Hi, title isn’t a very good descriptor but im kind of new to this so im not sure how to word it. My issue is that right now Im sending out a ray from a player and whenever it collides with a certain object and I press W, the player will change its transform.position to that of the object the ray hits and that works great no problems there. The issue is when I duplicate the object for the ray to hit and the player hits the duplicate, the transform.position of the player is set to the original position of the object.

I have the Sphere gameobject put into my public variable in the unity inspector and yeah. Any help would be greatly appreciated along with any corrections to my code would help a lot.

Here is the pretty basic code I have.

public float speed = 1f;
    float maxDistance = 1f;
    public GameObject Sphere;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        RaycastHit hit;
        Ray originF = new Ray(transform.position, Vector3.forward);

        Debug.DrawRay(transform.position, Vector3.forward * maxDistance);

        if (Input.GetKeyDown(KeyCode.W))
        {
            if(Physics.Raycast(originF, out hit, maxDistance))
            {
                if(hit.collider.isTrigger)
                {
                    transform.position = new Vector3(Sphere.transform.position.x, Sphere.transform.position.y, Sphere.transform.position.z);
                    Debug.Log("Hit");
                }
                
            }
        }
    }
}

In line 3 you define a GameObject Sphere, which you fill through the inspector. Then in Update you check whether you hit something, and if thats the case, you teleport to the location of THAT sphere. Instead, you seemingly want to teleport to the position of the hit object (possibly only if it is a sphere). You can get the hit object, and thus its position, from the raycasthit (hit) itself. Teleport to that, instead of your manually set sphere. If you want the raycast to only work on specific objects (spheres, for example), then create a new layer, put all those objects in there, and only cast the ray on that layer.

Raycasthit documentation: Unity - Scripting API: RaycastHit
You are interrested in the “transform” property, through which you can get the position of the hit object. You could also work with the hit-position itself if thats desired.

You are beautiful my dude. Thank you for the help

1 Like