两个脚本就是两个变量,但另一个脚本可以当作组件来调用另一个脚本的变量
脚本就是组件,可以用getcomponent来调用
例如:
假设脚本nvhai挂在物体Query-Chan-SD_Hiroshima (1)//这个是一个我游戏当中的女孩,下名字为nvhai.cs,想被获得的变量为Transform nvhaitr
假设脚本guaishou挂在物体怪兽下,名字为guaishou.cs,脚本guaishou想从物体Query-Chan-SD_Hiroshima (1)中获得变量nvhaitr
两步可以调用到
1,在nvhai.cs中,声明变量nvhaitr为public
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class nvhai : MonoBehaviour
{
public Transform nvhaitr;
public Animator nvhaian;
public Transform mctr;
public Rigidbody nvhairi;
public GameObject Ballyuan;
public Transform guntr;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
nvhaitr.Rotate(Vector3.up * Input.GetAxis("Mouse X"));
mctr.Rotate(Vector3.left * Input.GetAxis("Mouse Y"));
if (Input.GetKey(KeyCode.W))
{
nvhaitr.Translate(Vector3.forward * 0.01f);
nvhaian.SetBool("Run", true);
}
if (Input.GetKeyUp(KeyCode.W))
{
nvhaian.SetBool("Run", false);
}
if (Input.GetKey(KeyCode.S))
{
nvhaitr.Translate(Vector3.back * 0.01f);
nvhaian.SetBool("Run", true);
}
if (Input.GetKeyUp(KeyCode.S))
{
nvhaian.SetBool("Run", false);
}
if (Input.GetKey(KeyCode.A))
{
nvhaitr.Translate(Vector3.left * 0.01f);
nvhaian.SetBool("Run", true);
}
if (Input.GetKeyUp(KeyCode.A))
{
nvhaian.SetBool("Run", false);
}
if (Input.GetKey(KeyCode.D))
{
nvhaitr.Translate(Vector3.right * 0.01f);
nvhaian.SetBool("Run", true);
}
if (Input.GetKeyUp(KeyCode.D))
{
nvhaian.SetBool("Run", false);
}
if (Input.GetKeyDown(KeyCode.Space))
{
nvhairi.AddForce(Vector3.up * 200f);
nvhaian.SetBool("Jump", true);
}
if (Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject Ballcopy;
Ballcopy = Instantiate(Ballyuan, guntr.position, guntr.rotation);
Ballcopy.GetComponent<Rigidbody>().AddForce(guntr.forward * 800f);
Destroy(Ballcopy, 2f);
}
2.在guanshou.cs中,用Find()或者FiindWithTag()之类的方法查找到物体Query-Chan-SD_Hiroshima (1),然后用GetComponent<nvhai>().nvhaitr;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class guaishou : MonoBehaviour
{
Transform nvhaitr;//public Transform Girltr;
Vector3 mydes;//定义一个三维坐标常量,用来保存追踪目标的位置
// Start is called before the first frame update
void Start()
{
nvhaitr = transform.Find("Query-Chan-SD_Hiroshima (1)").GetComponent<nvhai>().nvhaitr;
}
// Update is called once per frame
void Update()
{
// mydes = GameObject.Find("Query-Chan-SD_Hiroshima (1)").GetComponent<Transform>().position;
//获得追踪目标位置
this.GetComponent<NavMeshAgent>().SetDestination(nvhaitr.position);
}
}