Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved How to Teleport Player to Instantiated Object Position

Discussion in 'Scripting' started by JungaBoon, Oct 12, 2020.

  1. JungaBoon

    JungaBoon

    Joined:
    Aug 4, 2020
    Posts:
    17
    I'm trying to achieve a teleport effect.
    I want to instantiate a Sword at a "fire point" in front of the player when they press a button. And then when they press another button, the player should teleport to where the Sword currently sits.
    I have this at the beginning of my script.

    public GameObject swordObject;
    public Transform firePoint;

    So when I press a button, it calls the first method:

    GameObject swordObj = Instantiate(swordObject, firePoint.transform.position, Quaternion.identity);


    And then when I press another button, it calls the second method:
    (This is where the teleport should happen).

    I separated the methods so that I could call them at specific times during an animation.
    How would I be able to reference the instantiated Sword's position in the second method so that I can teleport my player there? I just need to be able to reference the position of the instantiated object from a different method. Thanks.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    Perhaps keep track of it in a member variable instead of a local variable, then the other function can have at its position when it needs it.
     
  3. JungaBoon

    JungaBoon

    Joined:
    Aug 4, 2020
    Posts:
    17
    How would I be able to set the instantiated Sword object as a member variable?
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    A member variable is one declared outside of a function, just in class scope. Your
    swordObj
    above is a local variable (because you declare it there as a GameObject) so nobody else can get at it.
     
  5. JungaBoon

    JungaBoon

    Joined:
    Aug 4, 2020
    Posts:
    17
    Okay thank you! I got it working.
     
    Kurt-Dekker likes this.
  6. stickylab

    stickylab

    Joined:
    Mar 16, 2016
    Posts:
    88
    can you gimme da example please ,, i still dont understand
     
  7. JungaBoon

    JungaBoon

    Joined:
    Aug 4, 2020
    Posts:
    17
    Hi, which part did you still need help with?
     
  8. stickylab

    stickylab

    Joined:
    Mar 16, 2016
    Posts:
    88
    actualy idid fixed m,thanks