访问附加到另一个对象的脚本

时间:2017-03-12 15:14:30

标签: c# unity3d unity5 gameobject

我有一组代码附加到我的一个游戏对象上,我试图从另一个对象的脚本中访问它。

我正在尝试访问"移动"此脚本中的函数:

 using UnityEngine;
 using System.Collections;

 public class MoveBackwards : MonoBehaviour 
 {
     #region Inspector


     public float maxRotationDegrees = 10f;
     public float rotationSpeed = 2f;

     public float maxDistance = 5f;
     public float moveSpeed = 2f;

     #endregion //Inspector

     private float traveledDistance;
     private float rotatedAmount;
     private bool isMoving;

     #region Unity Engine & Events

     private void Update()
     {

         AudioSource audio = GetComponent<AudioSource>();

         if(isMoving)
         {
             if(traveledDistance < maxDistance)
             {
                 Vector3 moveDirection = -transform.up;
                 transform.position += moveDirection * moveSpeed * Time.deltaTime;
                 traveledDistance += Mathf.Abs(moveSpeed * Time.deltaTime);
             }
             if(rotatedAmount < maxRotationDegrees)
             {
                 transform.Rotate(0, 0, rotationSpeed * Time.deltaTime);
                 rotatedAmount += Mathf.Abs(rotationSpeed * Time.deltaTime);
             }
         }
     }

     #endregion //Unity Engine & Events

     public void Move()
     {

         isMoving = true;
     }

 }

使用此代码:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class PushbackAudio : MonoBehaviour {

     public AudioSource PushbackAudioPilot;
     public AudioSource PushbackApproved;
     public AudioSource PushbackApprovedPRB; //PRB = Pilot read back
     public bool running = true;

     public void AircraftPushbackAudioProcedure()
     {
         StartCoroutine(AircraftPushbackIEnumerator());
     }

    private IEnumerator AircraftPushbackIEnumerator()
     {
         running = true;

         while (running)
         {
             PushbackAudioPilot.Play();
             yield return new WaitForSeconds(7);
             PushbackApproved.Play();
             yield return new WaitForSeconds(5);
             PushbackApprovedPRB.Play();
             yield return new WaitForSeconds(5);
             MoveBackwards = GameObject.Find("Aircraft Sprite").GetComponent<Move>();


         }
     }
 }

我正在使用该行:MoveBackwards = GameObject.Find("Aircraft Sprite").GetComponent();,但它给了我两个错误:

  1. MoveBackwards是一种类型,但用作变量

  2. 类型或命名空间名称&#34;移动&#34;找不到(是你吗? 缺少使用指令或汇编参考?

  3. 知道如何解决这个问题吗?

    由于

1 个答案:

答案 0 :(得分:0)

  

我正在使用这条线:MoveBackwards = GameObject.Find(&#34; Aircraft   精灵&#34)GetComponent();但它给了我两个错误:

应该是:

MoveBackwards moveBc = GameObject.Find("Aircraft Sprite").GetComponent<MoveBackwards>();

然后您可以调用移动功能:

moveBc.Move();

<MoveBackwards>之前您只错过了()