我正在尝试使用Unity2D编写我的第一款游戏'Tappy Bird'。当我尝试运行应用程序时,我在Unity中收到以下错误消息:
Assets / scripts / TapController.cs(6,6):错误CS0592:属性 UnityEngine.RequireComponent对此声明类型无效。 它仅在类声明上有效
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
[RequireComponent(typeof(Rigidbody2D))]
public float tapForce = 10;
public float tiltSmooth = 5;
public Vector3 startPos;
Rigidbody2D rigidbody;
Quaternion downRotation;
Quaternion forwardRotation;
void Start()
{
rigidbody = GetComponent<Rigidbody2D();
downRotation = Quaternion.Euler(0, 0, -90);
forwardRotation = Quaternion.Euler(0, 0, 35);
}
void update()
{
if (input.GetMouseButtonDown(0))
{
transform.rotation = forwardRotation;
rigidbody.AddForce(vector2.up * tapForce, ForceMode2D.Force);
}
transform.rotation = Quaternion.Lerp(
transform.rotation, downRotation, tiltSmooth * Time.deltaTime);
}
void onTriggerEnter2D(Collider2D col){
if(col.gameObject.tag == "ScoreZone") {
//register a Score event
//play sound
}
if(col.gmeObject.tag == "DeadZone") {
//register a dead event
//play a sound
}
}
}
答案 0 :(得分:1)
如果我理解你的代码,你应该在类声明之前添加属性:
[RequireComponent(typeof(Rigidbody2D))]
public class NewBehaviourScript : MonoBehaviour
{
...
}
答案 1 :(得分:1)
需要在类之外设置将所需组件添加为依赖项的RequireComponent属性。
https://docs.unity3d.com/ScriptReference/RequireComponent.html
答案 2 :(得分:1)
https://docs.unity3d.com/ScriptReference/RequireComponent.html
首先,它应该在类名的前面;
第二,如果您已将脚本附加到游戏对象,则需要重新附加。
[RequireComponent(typeof(Rigidbody2D))]
public class NewBehaviourScript : MonoBehaviour
{
//...
}