简体   繁体   English

统一创建和销毁脚本组件时遇到问题

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

I am attempting to make it so you can add and remove a script from an object like a cube at the press of a button.我正在尝试制作它,以便您可以在 object 中添加和删除脚本,就像按下按钮的立方体一样。 This is what I've got so far, but it keeps throwing up an error expecting ";"这是我到目前为止所得到的,但它不断抛出一个错误,期待“;” & "{" on the same space [Line 24,71 after: if (Input.GetButtonDown("Button.Two")) GetComponent (Sticky))] & "{" 在同一空间 [第 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() ??? function Update()

    This is c# not unityscript .这是c#不是unityscript

  • Also GetComponent (Sticky) should rather be GetComponent<Sticky>() GetComponent (Sticky)也应该是GetComponent<Sticky>()

  • and what is if (Input.GetButtonDown("Button.Two")) GetComponent (Sticky)) supposed to do? if (Input.GetButtonDown("Button.Two")) GetComponent (Sticky))应该怎么做?

  • and in general you are missing like two closing } in your code and every statement ends with a ;通常,您的代码中缺少两个结束的} ,并且每个语句都以;结尾in c#c#

It should probably rather be eg它可能应该是例如

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