写在前面:
没有系统学过unity和C#,感觉在稍微复杂的问题面前就会方寸大乱,没有头绪。打算在1月补一下基础,感觉越到后面会越头秃,毕竟不能只靠博客和论坛学习吧。
正文:
我的需求是当血条加满时触发人物动画,也就是博客上常说的脚本之间的信息交互。
我一直是用arduino代码的视角去看C#,所以在这种问题上老是走死胡同。
我的人物动画用的是animator,也就是在设置动画过程中要用到状态机:
这个小东西。
关于animation和animator之间有什么不同的问题,我以前没想过,这次做的时候才不得不查了一下:animator可以通过状态机让动画之间有一定逻辑。
然后核心部分也比较清楚:血没加满→动画暂停;血加满了→动画播放。
代码示例:
(因为我的血条是由硬件控制的,VL53L0X测距传感器和arduino uno板,实时反馈距离信息,所以会出现血满了或者掉了变化急剧的现象,其实是我改变了障碍物距离【笑】)
血条:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using UnityEngine.UI;
public class Depthbar : MonoBehaviour
{
public Image HealthBar ;
public SerialPort sp = new SerialPort("COM9", 9600);
//public void SendMessage;
//public GameObject go1;
public int value;
//public GameObject human;
void Start()
{
sp.Open();
sp.ReadTimeout = 1;
}
void Update()
{
if (sp.IsOpen)
{
try
{
SetDepthBar(sp.ReadByte());
print(sp.ReadByte());
//human.SendMessage("Standup", "Direction", SendMessageOptions.RequireReceiver);
}
catch (System.Exception)
//此类是作为一种区分系统异常和应用程序异常的手段提供的。
{ }
}
}
void SetDepthBar(int Direction)
{
if (Direction == 0)
{
HealthBar.fillAmount = 0.0f;
}
if (Direction == 1)
{
HealthBar.fillAmount = 0.0f;
}
if (Direction == 2)
{
HealthBar.fillAmount = 0.2f;
}
if (Direction == 3)
{
HealthBar.fillAmount = 0.3f;
}
if (Direction == 4)
{
HealthBar.fillAmount = 0.4f;
}
if (Direction == 5)
{
HealthBar.fillAmount = 0.5f;
}
if (Direction == 6)
{
HealthBar.fillAmount = 0.6f;
}
if (Direction == 7)
{
HealthBar.fillAmount = 0.7f;
}
if (Direction == 8)
{
HealthBar.fillAmount = 0.8f;
}
if (Direction == 9)
{
HealthBar.fillAmount = 0.9f;
}
if (Direction == 10)
{
HealthBar.fillAmount = 1.0f;
}
}
}
人物:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ReceiveMessage : MonoBehaviour
{
//public Animation anim;
public Animator animator;
public float number=0f;
//public GameObject Image;
public Image HealthBar;
void Start()
{
animator = GetComponent <Animator>();
//HealthBar = Image.GetComponent<Image>();
}
private void Update()
{
number = HealthBar.fillAmount;
print(number);
Standup(number);
}
void Standup(float number)
{
if (number == 1.0f)
{
animator.speed = 1.0f;
}
else
{
animator.speed = 0.0f;
}
}
}
中间的注释掉的语句是我走过的弯路,没有别的意思。
成品截图: