Count

pihik

New member
Joined
Mar 26, 2021
Messages
2
Programming Experience
Beginner
Hello, my program is counting every second the object, I need to count it just when it is instantiate.

Thank you.
 
Please show us your code. Post it here in code tags. Not a screenshot, please.

We are not psychic. We cannot tell you why your program is behaving that way if we can't see how you put things together. It's possible you are misunderstanding the object lifetime and how garbage collection works.
 
If you're doing something every second then that suggests that you are using a Timer, although that's an educated guess that we shouldn't have to make because, as suggested, you should be providing all the relevant information. If you only want to count when an object is created then why would you have a Timer at all? Maybe there's another reason but, again, we have to guess because you haven't taken the time to explain.

In future, please provide a FULL and CLEAR explanation of the problem. Start by explaining exactly what you're trying to achieve. Follow that with exactly how you're trying to achieve it. That would include ALL the relevant code and ONLY the relevant code. Finish off with exactly what happens when you try and how and where that behaviour differs from your expectations. That would include any error messages and where they occur. Assume that we know nothing about your project, because that's the case. Give us all the relevant information. Finally, write a title that actually summarises the issue. Your problem is not counting. It is when to perform an action. What the action actually is isn't barely relevant.
 
C#:
{
    EnemySpawner enemySpawner;
    Text enemyText;
    [SerializeField] int enemies = 0;
    Enemy enemy;

    // Start is called before the first frame update
    void Start()
    {
        enemyText = GetComponent<Text>();
        enemySpawner = FindObjectOfType<EnemySpawner>();
    }

    // Update is called once per frame
    void Update()
    {
        RemainingEnemies();
        enemyText.text = enemySpawner.RemainingEnemies().ToString();
    }

    public void RemainingEnemies()
    {
        enemy = FindObjectOfType<Enemy>();
        enemies++;
    }
}
 
Last edited by a moderator:
Update() is called every time the game loop updates the game screen. This can happen multiple times a second. Your Update() is calling RemainingEnemies() twice which increments your enemies variable twice.
 

Latest posts

Back
Top Bottom