函数进入循环(重复自身)而不是只工作一次

Function got in cycle (repeats itself) instead of working just one time

我在另一个对象附近创建了 GameObject。函数 "Instantiate" 重复自身(进入循环),这就是问题所在。我只需要调用它一次。

我试过: 1.调用函数按下按钮(GetKey)。这个函数仍然创建 3-4 个对象。 2.在Update和FixedUpdate中添加代码。它仍然创建了几个对象。 :(

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

public class table : MonoBehaviour {

public GameObject obj;
public Renderer rend;

void Start () {

    rend = GetComponent<Renderer>();

    Vector3 center = rend.bounds.center;
    Vector3 pos = center + new Vector3 (12,0,0);

    Instantiate (obj, pos, Quaternion.identity);

}

}

okay

Not okay

您正在 Start 方法中调用函数 Instantiate (obj, pos, Quaternion.identity);。您的脚本 table 附加到您正在实例化的 GameObject,这意味着它会在每次 [=12] 时调用 Start 方法=] 生成,它将使用新脚本创建一个新脚本并调用该脚本的 Start 方法。

Possible solutions:
1. Move the line Instantiate (obj, pos, Quaternion.identity); to a method/function and call that function upon request
2. Remove the script table from your Prefab (in your case it's called obj in the script).