簡體   English   中英

統一創建和銷毀腳本組件時遇到問題

[英]Having issues creating and destroying a script component in unity

我正在嘗試制作它,以便您可以在 object 中添加和刪除腳本,就像按下按鈕的立方體一樣。 這是我到目前為止所得到的,但它不斷拋出一個錯誤,期待“;” & "{" 在同一空間 [第 24,71 行之后: if (Input.GetButtonDown("Button.Two")) GetComponent (Sticky))]

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

public class Sticky2 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
    function Update(){
         if (Input.GetButtonDown("Button.One"))
        {
        gameObject.AddComponent<Sticky>();
        }
    }

    function Update() {
         if (Input.GetButtonDown("Button.Two")) GetComponent (Sticky))
           Destroy (GetComponent (Sticky));
        }
    }



  • function Update()

    這是c#不是unityscript

  • GetComponent (Sticky)也應該是GetComponent<Sticky>()

  • if (Input.GetButtonDown("Button.Two")) GetComponent (Sticky))應該怎么做?

  • 通常,您的代碼中缺少兩個結束的} ,並且每個語句都以;結尾c#

它可能應該是例如

public class Sticky2 : MonoBehaviour
{
    private void Update()
    {
        // Use GetComponent in order to check if such componnet already exists
        if (Input.GetButtonDown("Button.One") && !GetComponent<Sticky>())
        {
            gameObject.AddComponent<Sticky>();
        }
    
        // Use TryGetComponent in order to check and get the component in one single go
        if (Input.GetButtonDown("Button.Two") && TryGetComponent<Sticky>(out var sticky))
        {
            Destroy(sticky);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM