- Home /
Unity Script not working in build, but does work in play mode
Hello, i have an unexplainable problem with Unity. I belive that a script gets disabled, or deletes itself while builded. Let me explain the issue. I have a unit that throws grenades on level 2, every 8 seconds. It works fine and dandy in play mode. When i Build the game however, the first grenade works like in play mode then all other grenades completely stop registering the script it has. Only collision and physics are detected after the first grenade. The way he throws them is very simple, Instantiate game object at grenade spawn location, then after addforce and rotate towards the target, while giving the Grenade script target position. Thrower of the grenade shares the Target position it has with the grenade script. The reason for this is that it spawns an explosion on the target to avoid any Damage loss because of game balance. There isn't any pooling with the objects whatsoever and i checked multiple times, but the only connection is between these two scripts:
Throwing Script
void Throw() {
if (!BetterGrenades)
{
GameObject go = Instantiate(Grenade, GrenadeSpawnPos.transform.position, GrenadeSpawnPos.transform.rotation);
go.GetComponent<Grenade_>().enabled = true;
go.GetComponent<Grenade_>().Target = this.Target.transform;
go.GetComponent<Rigidbody>().AddForce((Target.transform.position - transform.position) * (DistanceToEnemy), ForceMode.Impulse);
}
else
{
GameObject go = Instantiate(GrenadeV2, GrenadeSpawnPos.transform.position, GrenadeSpawnPos.transform.rotation);
go.GetComponent<Grenade_>().enabled = true;
go.GetComponent<Grenade_>().Target = this.Target.transform;
go.GetComponent<Rigidbody>().AddForce((Target.transform.position - transform.position) * (DistanceToEnemy), ForceMode.Impulse);
}
}
Grenade Throw Script
public GameObject Explosion; public Transform Target;
private void OnCollisionEnter(Collision collision)
{
if (Target != null)
{
Instantiate(Explosion, Target.position, Quaternion.identity);
Destroy(Explosion, 1.9f);
Destroy(gameObject);
}
else
{
Instantiate(Explosion, transform.position, Quaternion.identity);
Destroy(Explosion, 1.9f);
Destroy(gameObject);
}
}
Distance to enemy Calculation
float DistanceToEnemy = (transform.position - Target.transform.position).magnitude;
Answer by GhostSlayer44 · Jan 21 at 11:21 AM
Update: When i Build the game in Development build, after the first grenade every other grenade gives me an error -The Object you want to instantiate is null
Ok so um, this is kinda awkward. The problem was that in the Grenade throw script Destroy(Explosion,1.9f), destroys the Prefab completely so it doesn't have anything to spawn. Why does it work in Play mode and not in Build? I have no idea. But it works now, i dont get errors anymore. Any insight about the difference of build and play mode is appreciated