- Home /
 
Script Executing Multiple Times on a Single Object
Hello,
I am currently having trouble with my script in unity because it logs multiple times to the console. I may be unaware that this is just a change in Unity, but I would like to know why it is doing this.
Here is my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
 public class test : MonoBehaviour
 {
     // Start is called before the first frame update
     void Start()
     {
         
     }
 
     // Update is called once per frame
     void Update()
     {
         Debug.Log("gameObject " + gameObject.name, gameObject);
     }
 }
 
               The code is quiet generic for testing purposes, yet it appears three times in the console when I'm testing. I have checked many times to see if there is another object the script is attached to, but the script is only on this object. I have also tried it with different objects, and I have also recompiled my library to see if anything would fix the issue, but nothing seems to work. If there are any ideas on why this is happening, please let me know.
Thanks.
Answer by alexianphilosophy · Feb 04 at 02:22 AM
Hey, @AOG05. If I understand correctly, the code is running in the Update() function. The Update() function runs every frame, so it's expected to log that message every frame. It should actually just keep on running forever. There seems to be nothing stopping it from running forever, which is what it should do. If you want it executed once, put in the Start() function. 
Answer by AOG05 · Feb 04 at 02:54 AM
@alexzorzella, Thanks for the reply. I have noticed that the code was inside of the update function, but the log gets output three separate times in play mode. I've already checked to see if it was attached to anything else. 
So you have "Collapse" enabled. If you disable this, all the logs will end up going after each other in a long list. If you wait longer, do more messages appear, or do the numbers at the right of the console just increase? Maybe it's just separating them based on the time they were logged.
P.S. If you want to check the amount of instances of a script, you can try
 int instances = FindObjectsOfType<test>().Length;
 Debug.Log(instances);
 
                  in the Start() method. 
Thanks for the reply, it seemed that it is just something that I have not experienced in Unity before. When I put the logs into the start method, it only output one result instead of three. I thought that it was running the same script multiple times in the background, but it actually was not after all. Thanks for helping me figure out the issue to my question.
Your answer