Tried posting this in unity answers but got “The form below has errors. Correct the fields in red and try again.” Even though there are no red fields.
In my scene I have a muzzle object parented to a gun, and the gun is parented to the player. As scene objects, everything was working fine, but when I converted the gun to a prefab the member variables become incorrect. The gun prefab is assigned to a PlayerScript.cs in the inspector and instantiated like this:
Instantiate(m_shotgun, transform.position, transform.rotation);
My input manager is then retrieving the gun prefab from the PlayerScript.cs then calling the ShootGun public function. How can this value be false?
The gun prefab then has a script with public bool m_canShoot = true;
. Even though it is never assigned to false and the inspector says it is true, the debugger has it as false. Weirdly enough this value is correct in the “Update” function but not in the ShootGun function.
I must have some misunderstanding of how these member functions work. When I log to the console the position of the “m_muzzle” gameobject in the Update function, it changes as expected. But when I log it’s position in the ShootGun() function, it remains the same always. Here is the full c# script:
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class GunScript : MonoBehaviour
{
public string m_gunName;
public GameObject m_bullet;
public float m_fireRate;
public float m_damage;
//private Animator m_anim;
public Animator m_muzzleAnim;
public GameObject m_muzzle;
public bool m_canShoot = true;
private float m_shootTimer;
void Awake()
{
// always parent this to the player
transform.parent = GameObject.FindGameObjectWithTag("Player").transform;
m_shootTimer = Time.time;
}
private void Update()
{
if (!m_canShoot)
{
// fire rate per second
float fireRateSec = 1f / m_fireRate;
if (Time.time - m_shootTimer >= fireRateSec)
{
m_canShoot = true;
m_shootTimer = Time.time;
}
}
}
public void ShootGun()
{
Debug.Log(m_muzzle.transform.position);
if (true)
{
if (m_muzzle != null) //muzzle flash and camerashake
{
m_muzzleAnim.Play("Muzzle_" + m_gunName + "_Shoot");
CameraShake.Shake(0.075f, 0.1f, 3f);
}
else {
Debug.LogWarning("Muzzle not assigned in gun script.");
}
if (m_bullet != null) //create bullet
{
float angle = Common.PlayerMouseAngle();
Instantiate(m_bullet, m_muzzle.transform.position, Quaternion.Euler(new Vector3(0f, 0f, angle)));
}
else {
Debug.LogWarning("Bullet not assigned in gun script.");
}
m_canShoot = false;
}
}
}