- Home /
Script inside instantiated prefab run lag behind
Hi everyone, newbie here. I have a problem which script written inside instantiated prefab seem running a bit behind the main script (the script which instantiate the prefab.) I re-write and simplify the script below to simplify the question: The first script: "Counting1" using UnityEngine;
public class Counting1 : MonoBehaviour
{
public Transform counting2Prefab;
public int count1;
public static int passCount;
public float time = 2f;
public float delay;
void Start()
{
count1 = 0;
delay = time;
}
void Update()
{
if (delay <= 0)
{
GetCounting();
delay = time;
}
delay -= Time.deltaTime;
}
void GetCounting()
{
SpawnCounting2();
Debug.Log("count1 = " + count1);
passCount = count1;
GetSum();
Debug.Log("count3 = " + count1);
}
void SpawnCounting2()
{
Instantiate(counting2Prefab, transform.position, transform.rotation);
}
void GetSum()
{
count1++;
}
}
The second script= "Counting2" using UnityEngine;
public class Counting2 : MonoBehaviour
{
private static int count2;
void Start()
{
count2 = Counting1.passCount;
Debug.Log("count2 = " + count2);
Destroy(gameObject);
}
}
I need the counting order to be: count1, and then count2, and then count3. But if you run the script above, the order always become: count1, and then count3, and then count2.
The count2 which written inside second script seems always running lag behind. Any way to do it so count2 will be executed before count3? Should i use something like coRoutine?
Thanks for the time!
Answer by Casiell · Apr 13, 2020 at 12:31 PM
Instead of Start in Counting2 class use Awake. Awake will be called at the exact moment when you are instantiating a prefab, before execution goes any further. Start is called somewhere later, but I'm not exactly sure when.
i tried to put all the coding inside Awake in Counting2 class. The order somehow changed, become: count2, count1, count3. but the calculation still lagging. Actual first calculation: count2 = 0 count1 = 0 count3 = 1 Second calculation: count2 = 0 count1 = 1 count3 = 2 Note that the count2 in the second calculation is sitll at 0. it supposed to be 1.