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. 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))]
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()
???
This is c#
not unityscript
.
Also GetComponent (Sticky)
should rather be GetComponent<Sticky>()
and what is if (Input.GetButtonDown("Button.Two")) GetComponent (Sticky))
supposed to do?
and in general you are missing like two closing }
in your code and every statement ends with a ;
in 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);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.