Home > OS >  My code runs more than one time in the whole Unity project
My code runs more than one time in the whole Unity project

Time:07-04

Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TankItemScript : MonoBehaviour
{   
    public GameObject tankFollowerPrefab;
    public bool a = true;
    public GameObject laptopPrefab;

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            GameObject tank = Instantiate(tankFollowerPrefab, new Vector3(transform.position.x, transform.position.y, transform.position.z - 1.5f), Quaternion.identity, transform);
            Destroy(gameObject);
        }
    }

    void Update()
    {
        transform.Rotate(0f, 0.2f, 0f);
    }

    void Start()
    {
        if (a == true)
        {
            Instantiate(laptopPrefab, new Vector3(transform.position.x, transform.position.y   1f, transform.position.z), transform.rotation);
            a = false;
        }
    }
}

void Start() running 3 times. Even with checking that I running it ONE time.

There is no other scripts that are affecting this script. My laptop prefab is used only in this code.

Why instead of one laptop it spawns 3-4? How to fix it? The problem is that it's happening not only with this script, but with others too! Instead of adding 1 to my variable, it adds 3!

Even more, it worked before! I feel that memes become reality D:

CodePudding user response:

Your problem is most likely that you put this script (with this start function) on more than one object and then every object calls its start function.

CodePudding user response:

russ lang

возможно, я не правильно понял вопрос, но не пробовали ли вы убрать этот код из update метода? eng lang perhaps I misunderstood the question, but have you tried to remove this code from the update method?

  • Related