Swap Gameobjects Runtime [Closed]

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.

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.

The code is far too long to post. I’ll quickly write up pseudo-code.

public Gameobject objectHeld;
public Gameobject crowbar;

Start(){
     objectHeld = crowbar;
}

OnTriggerEnter2D(Collider2D col){
     if(col.gameobject.tag == "Weapon" && Input.GetKeyDown(KeyCode.E){
        objectHeld = col.gameobject; 
     }
}

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? :slight_smile:

Thanks,

  • Keith
if(col.gameobject.tag == "Weapon"&&Input.GetKeyDown(KeyCode.E){

I think your error may be there. You’d have to press E exactly when you enter the trigger zone.
Try using OnTriggerStay2D.
http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerStay2D.ht

1 Like

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