I have a class Projectile which is attached to a prefab that gets instantiated by my weapon. In it, there is the floating point energyLevel which is initialized at a value of 4f. This is a multiplier that factors into the speed of the transform, propelling the projectile.
For some reason, this value is getting reset to 0f on instantiation, and I can’t figure out why.
Projectile.cs
using System.Collections.Generic;
using UnityEngine;
using MEC;
public class Projectile : MonoBehaviour
{
public float energyLevel = 4f;
public Vector3 aimDirection;
void Start() => Timing.RunCoroutine(Travel());
IEnumerator<float> Travel()
{
while (true)
{
print(energyLevel);
transform.position += Vector3.ClampMagnitude(aimDirection, 1f) * energyLevel * Timing.DeltaTime;
yield return Timing.WaitForOneFrame;
}
}
}
The instantiation takes place in class Shoot. Here you can see that I instantiate the prefab normally, but I cache the instance of the script attached to it (Projectile.cs) for modification. The only value I am modifying currently is aimDirection which is printing to console with the correct magnitude. I do not touch energyLevel here, or anywhere else. Its lifecycle is purely within the scope of Projectile (at this point).
Shoot.cs
using UnityEngine;
public class Shoot : MonoBehaviour
{
[SerializeField] Transform cannon = null;
[SerializeField] GameObject projectile = null;
public void Cannon(State state)
{
var shot = Instantiate(projectile, cannon.position, state.aimRotation);
var shotProperties = shot.GetComponent<Projectile>();
shotProperties.aimDirection = state.aimDirection;
print(shotProperties.aimDirection);
}
}
What could be causing this? When I replace the energyLevel variable with a literal value of 4f in the transform.position operation, it works. When I put energyLevel back in, it doesn’t, and energyLevel logs to console as 0. Very confused, lol.