I’ve been trying to implement a script for switching weapons in my game, but the array I use to hold all of the GameObjects that represent my weapons always shows up as 0 outside of the Start() method. How can I fix this to make it functional? I have attached the script I am using to do this, which is the same script that I use for movement.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement : MonoBehaviour
{
private Rigidbody rb; // rb = rigidbody of player
public bool isGrounded;
[SerializeField] public float jumpHeight;
[SerializeField] public float speed;
public GameObject bulletPrefab;
public GameObject pistol;
public GameObject empty;
public Camera playerCamera;
public GameObject[] weapons = new GameObject[2];// = {empty, pistol};
public int currentWeapon = 1;
public int numWeapons;
//float trueSpeed;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
GameObject[] weapons = { empty, pistol };
numWeapons = weapons.Length;
Debug.Log("length of arr: " + weapons.Length); ;
//SwitchWeapon(0);
Debug.Log(numWeapons);
}
// Update is called once per frame
private void OnCollisionEnter(Collision collision)
{
isGrounded = true;
//Debug.Log("on ground");
}
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.forward);
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontalInput, 0f, verticalInput);
//float speedtotal(direction * speed* Time.deltaTime);
//Debug.Log (speedtotal);
//Vector3 direction = (forward * horizontalInput * speed) + (right * verticalInput * speed);
transform.Translate(direction * speed * Time.deltaTime);
//Debug.Log(controller.isGrounded);
if ((Input.GetKeyDown(KeyCode.Space)) && isGrounded) //(rb.velocity.y==0))
{
rb.velocity = new Vector3(0, jumpHeight, 0);
if (isGrounded == true)
{
Debug.Log("on ground also");
}
isGrounded = false;
}
if (Input.GetMouseButtonDown(0))
{
print("The Left mouse button was clicked");
GameObject bulletObject = Instantiate(bulletPrefab);
bulletObject.transform.position = playerCamera.transform.position + playerCamera.transform.forward;
bulletObject.transform.forward = playerCamera.transform.forward;
}
if (Input.GetKeyDown(KeyCode.Alpha1)) {
Debug.Log("length of arr outside of Start: " + weapons.Length);
SwitchWeapon(0, weapons);
}
if (Input.GetKeyDown(KeyCode.Alpha2)) {
SwitchWeapon(1, weapons);
}
}
void SwitchWeapon(int index, GameObject[] weapons)
{
for (int i = 0; i < numWeapons; i++)
{
Debug.Log(i);
if (i == index)
{
Debug.Log("i=index");
Debug.Log("length of arr in method: " + weapons.Length);
weapons[i].SetActive(true);
weapons[currentWeapon].SetActive(false);
currentWeapon = index;
}
}
}
}