I have coded this to change weapons in my fps game. The weapon change, start() and SelectWeapon() functions work properly but the update() function doesn’t work at all.
using UnityEngine;
public class WeaponControllerSwitching : MonoBehaviour
{
public int selectedWeapon = 0;
// Start is called before the first frame update
void Start()
{
SelectWeapon();
}
// Update is called once per frame
void Update()
{
int previousSelectedWeapon = selectedWeapon;
Debug.Log("Updating");
if (Input.GetAxis("Mouse ScrollWheel") > 0f)
{
if (selectedWeapon >= transform.childCount - 1)
selectedWeapon = 0;
else
selectedWeapon++;
}
if (Input.GetAxis("Mouse ScrollWheel") > 0f)
{
if (selectedWeapon <= transform.childCount - 1)
selectedWeapon = 0;
else
selectedWeapon--;
}
if (previousSelectedWeapon != selectedWeapon)
{
SelectWeapon();
}
}
void SelectWeapon()
{
int i = 0;
foreach (Transform weapon in transform)
{
if (i == selectedWeapon)
weapon.gameObject.SetActive(true);
else
weapon.gameObject.SetActive(false);
i++;
}
}
}
What do you mean with “doesn’t work at all.” Please elaborate and explain. Do you mean that your Update function does not run at all? Or do you mean that the code in your Update does not do what you imagine it should do? Or something else, like you get some errors you don’t know how to deal with?
If you put to your Update something like: Debug.Log("Update running.");
Do you see anything in your console window? Always first check the basics if something seems to be failing.
EDIT: just out of curiosity I checked your code, it does run just fine here, no errors when compiling. So there must be some logic error how you expect it to function. Or there’s that unlikely situation that the Update really doesn’t run. But try that Debug print first to see if it’s running there.
I assume that the Update function is called, but doesn’t result in anything happening.
Reason for this is that you have 2 if-clauses that compare the same thing “if (Input.GetAxis(“Mouse ScrollWheel”) > 0f)”. The second one probably needs to be “< 0f”.
What currently happens is that the first if-clause does selectedWeapon++ and then the second if-clause does selectedWeapon-- … essentially putting you on the weapon you started with again. So no weapon is switched.
I’m fairly certain that at some point this object is getting disabled or destroyed, and this will help you find out where. If you see this line, click on it in the console, and look at the lines below it in the console. That’s called the stacktrace, and it’s basically the path the code took to get to that function. If you check out where it came from, you should be able to see why it got disabled.