[英]The attribute UnityEngine.RequireComponent is not valid on this declaration type. It is valid on class declarations only
I am trying to code my first game 'Tappy Bird' using Unity2D.我正在尝试使用 Unity2D 编写我的第一个游戏“Tappy Bird”。 When I try to run the app, I am receiving the following error message in Unity:
当我尝试运行该应用程序时,我在 Unity 中收到以下错误消息:
Assets/scripts/TapController.cs(6,6): error CS0592: The attribute UnityEngine.RequireComponent is not valid on this declaration type.
Assets/scripts/TapController.cs(6,6):错误 CS0592:属性 UnityEngine.RequireComponent 在此声明类型上无效。 It is valid on class declarations only
它仅对类声明有效
Code:代码:
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
}
}
}
If I understand your code right you should add attribute before class declaration:如果我理解你的代码正确,你应该在类声明之前添加属性:
[RequireComponent(typeof(Rigidbody2D))]
public class NewBehaviourScript : MonoBehaviour
{
...
}
The RequireComponent attribute that adds required components as dependencies needs to be set outside of your class.添加所需组件作为依赖项的 RequireComponent 属性需要在您的类之外设置。
https://docs.unity3d.com/ScriptReference/RequireComponent.html https://docs.unity3d.com/ScriptReference/RequireComponent.html
https://docs.unity3d.com/ScriptReference/RequireComponent.html https://docs.unity3d.com/ScriptReference/RequireComponent.html
Firstly, it should be in front of the class name;首先,它应该在类名的前面;
Secondly, if you have attach the script to gameobject, you need to reattach again.其次,如果您已将脚本附加到游戏对象,则需要再次重新附加。
[RequireComponent(typeof(Rigidbody2D))]
public class NewBehaviourScript : MonoBehaviour
{
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.