i have a relatively noobish system of weapon switching, activating and deactivating objects on a player object, but the objects and its children stay activated on runtime though there are no errors in the console. Here’s the script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WeaponSwitcher : MonoBehaviour {
public GameObject blaster;
public GameObject blaster2;
public void Awake(){
blaster = GameObject.Find("Blaster");
blaster2 = GameObject.Find("Blaster2");
blaster.SetActive(true);
blaster2.SetActive(false);
}
public void Update()
{
if (Input.GetKeyDown("space"))
{
Debug.Log("Update Here!");
blaster.SetActive(false);
blaster2.SetActive(true);
}
}
}
Are you sure that awake and update is called? Your WeaponSwitcher class does not derive from MonoBehaviour and Awake and Update is specified private (which cannot be called from outside). If you are not deriving from MonoBehaviour - how did you attach the script to a game object?
You can also put some debug loggin into the awake and update method do see if it is called, or attach the debugger to unity and set a breakpoint.
Are you sure that update is not called?
I’m thinking more that the if clause is never fulfilled. Try to use the KeyCode.Space enum instead of the string if you want to poll the space key directly (Unity - Scripting API: KeyCode.Space).
After a bit of deeper googling and reading the manual, i think i have to move the awake method to update method for object to deactivate, and reactivate the object via coroutine. I’ll check it out later.
By moving the awake method to update i meant moving the body from the Awake() to Update()
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WeaponSwitcher : MonoBehaviour {
public GameObject blaster;
public GameObject blaster2;
void Update()
{
blaster = GameObject.Find("Blaster");
blaster2 = GameObject.Find("Blaster2");
blaster.SetActive(true);
blaster2.SetActive(false);
{
if (Input.GetKeyDown("space"))
{
StartCoroutine(Switch ());
}
}
}
IEnumerator Switch ()
{
yield return null;
blaster.SetActive(false);
blaster2.SetActive(true);
}
}
There’s only one of each blaster and blaster2 objects and the script is in the scene, of course, on a parent object. The first part of the script now works, blaster2 is disabled, but the coroutine is not switching objects active/unactive state.
Wait. do you have the first part of the script in update? You do realize that even if your coroutine runs, your update will hit, thus enabling blaster and disabling blaster2 again, right?