Search Unity

Swap Gameobjects Runtime [Closed]

Discussion in 'Scripting' started by Keith90, Jun 30, 2015.

  1. Keith90

    Keith90

    Joined:
    Sep 27, 2013
    Posts:
    116
    Hello,

    Currently I'm in a bit of a pickle. I'm trying to accomplish something which for some reason just won't work.

    Basically, what I'm trying to achieve is be able to swap what gameobject is assigned to a variable during runtime.

    For example:

    Game starts, character is holding object which is assigned to the variable objectHeld. When the character walks over another object on the floor and it's in the character's trigger, I press a key which then should swap what the character is holding with the object on the floor. However, it seems Unity doesn't like having the inspector change during runtime. I have even tried making the character drop the held object and made the variable be null but that doesn't work either.

    Does anyone have any ideas or solutions to this problem? I seem to be stumped.

    Thanks for your time.

    - Keith.
     
  2. Korno

    Korno

    Joined:
    Oct 26, 2014
    Posts:
    518
    Will need to see some code...

    What do you mean inspector change? You mean variables change? There is nothing wrong with Unity - you are doing something wrong.

    Please post the relevent code. The code for the player when he enters the trigger.
     
  3. Keith90

    Keith90

    Joined:
    Sep 27, 2013
    Posts:
    116
    The code is far too long to post. I'll quickly write up pseudo-code.

    Code (csharp):
    1.  
    2.  
    3. public Gameobject objectHeld;
    4. public Gameobject crowbar;
    5.  
    6. Start(){
    7.      objectHeld = crowbar;
    8. }
    9.  
    10. OnTriggerEnter2D(Collider2D col){
    11.      if(col.gameobject.tag == "Weapon" && Input.GetKeyDown(KeyCode.E){
    12.         objectHeld = col.gameobject;
    13.      }
    14. }
    15.  
    16.  
    The variable in the inspector stays to the original object, it won't swap to anything else. So you could please point out what I'm doing wrong and point me on the right path? :)

    Thanks,

    - Keith
     
  4. GNGification

    GNGification

    Joined:
    Oct 24, 2013
    Posts:
    59
    Korno likes this.
  5. Keith90

    Keith90

    Joined:
    Sep 27, 2013
    Posts:
    116
    Hahaha.

    I have no idea why I was using OnTriggerEnter. Such a simple mistake. Another mistake I figured out is that I should have just used GetKey instead of GetKeyDown.

    Thanks for your help gentlemen. I appreciate it.

    - Keith