Unity bug gives false error messages or doesen't work without a Debug.Log() line present
So I wanted to make a simple projectile damage on collision script. But since the projectile is a prefab, i cannot drag and assign my player as the target. Thats why i wanted to leave the player gameobject empty and assign it via script. But even though it works, it gives me an error that the player isn't assigned every time the bullet spawn:
private Health health; public GameObject player;
void Start()
{
if (player == null){
player=GameObject.FindGameObjectWithTag("Player");
}
health=GameObject.FindGameObjectWithTag("Player").GetComponent<Health>();
}
void OnCollisionEnter2D(Collision2D col){
if(col.gameObject.tag==player.tag){
health.DecreaseHealth();
}
Destroy(gameObject);
}
So me not wanting to have an error message, I removed the player gameobject:
private Health health;
void Start()
{
health=GameObject.FindGameObjectWithTag("Player").GetComponent<Health>();
}
void OnCollisionEnter2D(Collision2D col){
Debug.Log(player.tag);
if(col.gameObject.tag==GameObject.FindGameObjectWithTag("Player").tag){
health.DecreaseHealth();
}
Destroy(gameObject);
}
and when I do this, it doesen't even create the bullet, which I do in a totally different script.It will only work like this if i put the Debug.Log command there with the player.tag as argument.
Are both of these bugs or am I doing something wrong?,So I was using "public GameObject player" to assign my player, and but when I do, it constantly spams error messages that it isn't assigned, which it isn't in the inspector, but it is in the script in start.
please share the errors and the lines where they appear. this cant give you an error
if (player == null){
player=GameObject.FindGameObjectWithTag("Player");
}
and adding/removing the debug.log is for sure not the issue. what do you mean that works? that doesnt gives error messages? how is the debug.log player.tag even compile if you removed the player var?
Answer by AAcat · Jul 28, 2019 at 09:47 PM
I don't know if this helps, but try changing "void start" to "void awake". This usually helps with initialization and errors of the likes. ( Also the error code and line helps to know too :v )
as i said in my comment is imposible that these line gives an error
if (player == null){
player=GameObject.FindGameObjectWithTag("Player");
}
the debug.log is not getting affected, is the player spawned / destroyed by code? the debug.log cant be causing the issue and most likely is not a unity bug
Your answer
Follow this Question
Related Questions
Can't add Orbital script - "The script needs to derive from MonoBehaviour!" 0 Answers
Multiple .dll files missing, right after installing Unity 0 Answers
I need someone to help me: error CS1525: Unexpected symbol `void' 0 Answers
Unity doesn't open for me. 0 Answers
Why the Unity is not opening? 0 Answers