Unity脚本之间的交互
前言
脚本挂载到物体上就成为了类似RigBody和Material这种组件,所以也是可以在其他脚本中调用的;
本文也搭配有视频演示(文章末尾)
开工
1.首先规划一下要实现的功能和思路,比如实现角色的生命值和UI上的血条进行同步的效果
2.新建一个名为Playe的胶囊体,添加RigBody组件和创建一个名为PlayerS的C#脚本,具体看下图或演示视频
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerS : MonoBehaviour {
public float health = 100; // 角色健康值
public float speed = 5; // 角色移动速度
private Rigidbody rig;
// Use this for initialization
void Start () {
rig = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
rig.velocity = new Vector3(Input.GetAxis("Horizontal")*speed, 0, Input.GetAxis("Vertical")*speed);
}
// 添加碰撞检测
void OnCollisionEnter(Collision col)
{
if(col.gameObject.name == "Hurt")
{
// 当Player每碰撞一次Hurt的时候,将它的健康值减百分之10;
if(health > 0)
{
health -= 10;
}
print("Health = " + health);
}
}
}
3.再建一个名为Hurt的Cube物体,不做任何组件和属性的修改
4.到目前为止就实现了下面的GIF图一样的效果,Player每碰撞一次Hurt就会减百分之10的健康值(health)
5.现在再来创建一个Text UI,添加一个名为HealthUI的C#脚本,UI的属性设置看自己习惯
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthUI : MonoBehaviour {
private GameObject player; // 定义角色
private PlayerS PlayerS; // 角色上挂载的脚本
private float getHealth; // 定义角色的健康值
private Text text; // text UI
// Use this for initialization
void Start () {
player = GameObject.Find("Player"); // 获取角色
PlayerS = player.GetComponent<PlayerS>(); // 获取角色上的脚本
text = GetComponent<Text>(); // UI组件
}
// Update is called once per frame
void Update () {
getHealth = PlayerS.health; // 获取角色健康值
text.text = getHealth.ToString("0"); // 将 Text UI的值改为角色的健康值
}
}
6.完工,洗洗睡了!!!