(C#) Stack overflow caused by unknown operation
Hi. My editor keeps crashing because of a stack overflow. The error message is as follows:
I can't seem to find an infinite loop in my code and i'm stumped as I can't find an answer anywhere. The error message can not be expanded as far as I know. When double clicking the messages two objects are highlighted in my hirarchy and these are the scripts asociated with them (ignore the dutch comments);
using UnityEngine;
using System.Collections;
using UnityStandardAssets._2D;
public class Weapon : MonoBehaviour
{
// De schade die het wapen toebrengt
public int Damage;
// Pak de Bullet emitter
public GameObject Bullet_Emitter;
// Pak de bullet uit
public GameObject Bullet;
// Snelheid van de kogel
public float Bullet_Forward_Force;
// Hoeveelheid kogels
private int bulletAmount;
// Positie om te schieten
private Vector3 positionLeft;
// Positie om te schieten
private Vector3 positionRight;
// Positie bepaling
private bool facingLeft = false;
// Enemy ??
private Enemy enemy = new Enemy();
// Methode om te het aantal kogels op het scherm te verminderen met 1 wanneer er een kogel vernietigd wordt
void bulletAmountMinusOne()
{
bulletAmount -= 1;
}
//De kogel vernietigen wanneer deze een enemy raakt en schade toebrengen
//void OnTriggerEnter(Collider other)
//{
// if (other.gameObject.tag == "Enemy")
// Destroy(other.gameObject);
// Debug.Log("Hit");
//}
//void OnCollision2DEnter(Collision col)
//{
// if (col.gameObject.tag == "Enemy")
// {
// Destroy(this.transform);
// enemy.DamageEnemy(Damage);
// }
//}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftArrow)) // Hier checken voor input is niet ideaal maar wist niet hoe anders
{
facingLeft = true;
}
if (Input.GetKey(KeyCode.RightArrow))
{
facingLeft = false;
}
if (Input.GetKeyDown("p") && bulletAmount < 3)
{
shoot();
}
}
void shoot()
{
// Richting om in te schieten
positionLeft = new Vector3(-10, 0);
positionRight = new Vector3(10, 0);
// Schieten
// Bullet aanmaken
GameObject Temporary_Bullet_Handler;
Temporary_Bullet_Handler = Instantiate(Bullet, Bullet_Emitter.transform.position, Bullet_Emitter.transform.rotation) as GameObject;
bulletAmount += 1; // Moet anders
// Haal de rigidbody van de geinstantieerde kogel op en en bestuur deze
Rigidbody temporary_RigidBody;
temporary_RigidBody = Temporary_Bullet_Handler.GetComponent<Rigidbody>();
if (facingLeft == true)
{
// De snelheid van de kogel toevoegen aan de sneldheid van de rigidbody
temporary_RigidBody.AddForce(positionLeft * Bullet_Forward_Force);
}
else
{
temporary_RigidBody.AddForce(positionRight * Bullet_Forward_Force);
}
// De kogel vernietigen
Invoke("bulletAmountMinusOne", 2);
Destroy(Temporary_Bullet_Handler, 2.0f);
}
}
And
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
Weapon weapon = new Weapon();
[System.Serializable]
public class EnemyStats
{
public int Health = 100;
public int DamageOnHit = 20; // Variabel?
}
public EnemyStats enemyStats = new EnemyStats();
public Player player = new Player();
public void DamageEnemy(int damage)
{
enemyStats.Health -= damage;
if (enemyStats.Health <= 0)
{
GameMaster.KillEnemy(this);
}
}
//void OnCollision2DEnter(Collider2D col)
//{
// // Schade toebrengen aan de speler wanneer hij de vijand aanraakt
// if (col.gameObject.tag == "Player")
// {
// player.DamagePlayer(enemyStats.DamageOnHit);
// }
// if (col.gameObject.tag == "Bullet")
// {
// DamageEnemy(weapon.Damage);
// Destroy(col.gameObject);
// Debug.Log("We hit");
// }
//}
//void OnTriggerEnter2D(Collider2D other)
//{
// Debug.Log("Hit" + other.GetComponent<Collider>().name + "For");
// Destroy(other.gameObject);
//}
}
It seems no matter what I comment out the overflow keeps happening and crashing my editor. So my question is is there a fatal error in the code, or is there a possibility of the set up in the editor causing the overflow? If additional information is needed I'll provide it. Thanks in advance.
Answer by Bunny83 · Nov 22, 2016 at 04:28 PM
Remove the = new Weapon()
in this line
Weapon weapon = new Weapon();
First of all you can't create MonoBehaviour derived classes with "new". They have to be attached to a GameObject. If you want to dynamically create one you have to use AddComponent<Weapon>()
on a GameObject to create an instance.
However in most cases you usually assign references in the inspector by dragging the object you want to reference onto the variable. For this your variable either need to be public or marked with the SerializeField attribute:
// either
public Weapon weapon;
//or
[SerializeField]
Weapon weapon;
The same is true for those lines:
private Enemy enemy = new Enemy();
public Player player = new Player();
At the moment when an Enemy is created you implicitly create a new Weapon instance. The Weapon on the other hand creates a new Enemy instance. So you have an infinite recursion which will lead to a stack overflow
That did it, thank you so much. I've been studying C# a lot but i'm still a noob when it comes to Unity. I'll make sure to remember this.
Your answer
Follow this Question
Related Questions
StackOverflowException, cant find out how to fix it 0 Answers
Inexplicable error 0 Answers
Unknown Error! PLZ HALP!!11 0 Answers
what does this error mean? javascript 0 Answers
Stack pop and push for unityscript? 0 Answers