gpt4 book ai didi

c# - 从另一个脚本访问start()函数错误?

转载 作者:行者123 更新时间:2023-12-02 10:46:49 25 4
gpt4 key购买 nike

我如何从另一个脚本访问start()函数,因为启动函数只能定义一次

这是包含start()的脚本-

using UnityEngine;
using System.Collections;

public class MoverBolt : MonoBehaviour {
public PlayerControl obj ;
public float speed ;
public Rigidbody rb;

void Start(){
rb = GetComponent<Rigidbody>();
rb.velocity = transform.forward * speed;

}
}

需要访问start()的脚本
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Boundary{
public float xMax,xMin,zMax,zMin;
}
public class PlayerControl : MonoBehaviour
{
public Boundary boundary ;
public float velocity;
public float tilt;
MoverBolt obj = new MoverBolt();
/* I made an object but it seems you are not supposed to create an object of class which is inheritance of MonoBehaviour */

void FixedUpdate()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
obj.rb.velocity = movement*velocity;
Vector3 current_position = obj.rb.position;
obj.rb.position = new Vector3 ( Mathf.Clamp(current_position.x,boundary.xMin,boundary.xMax),
0.0f,
Mathf.Clamp(current_position.z, boundary.zMin, boundary.zMax)
);
obj.rb.rotation= Quaternion.Euler(0.0f,0.0f,obj.rb.velocity.x*-tilt );
}

}

Error You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent().



还有其他选择吗?

最佳答案

可以从外部调用Start()方法。只是公开。

public class MoverBolt : MonoBehaviour {
public void Start ()
{
Debug.Log("MoverBolt.Start() was called");
}
}

public class PlayerControl : MonoBehaviour {
[SerializeField]
private MoverBolt _moverBolt;

void Start ()
{
_moverBolt.Start();
}
}

控制台的输出是
MoverBolt.Start() was called
MoverBolt.Start() was called

更新1

我不建议这样做,因为Start()方法由您的代码和游戏引擎再次调用。

当我需要确保MonoBehaviour的设置正确时,在另一个类使用它之前。我将Awake/Start方法替换为 public void Initialize()方法,并从外部调用它。

关于c# - 从另一个脚本访问start()函数错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com