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

时间:2015-08-08 06:03:53

标签: c# unity3d compiler-errors

如何从另一个脚本访问start()函数,因为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 );
   }

 }
  

错误您正尝试使用'new'关键字创建MonoBehaviour。这是不允许的。 MonoBehaviours只能使用AddComponent()添加。

还有其他选择吗?

3 个答案:

答案 0 :(得分:1)

可以从外部调用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时,在另一个类使用它之前。我用public void Initialize()方法替换了Awake / Start方法,并从外部调用它。

答案 1 :(得分:0)

非常简单的回答。您无法从任何其他脚本访问start()函数。

答案 2 :(得分:0)

使用“实例化”。例如,您可以创建要复制的游戏对象的预制件,然后使用预制件生成新对象。

public class ObjectFactory : MonoBehaviour()
{
   public GameObject prefab;  // Set this through the editor.

   public void GenerateObject()
   {
      // This will create a copy of the "prefab" object and its Start method will get called:
      Instantiate(prefab);
   }
}