34、物品基类
新建Powerup.cs,并添加代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class Powerup : NetworkBehaviour
{
// mirror将NetworkInstanceId替换成uint
[HideInInspector] [SyncVar] public uint parentID;
private ObjectSpawner spawner;
public override void OnStartClient()
{
// 找到物品
GameObject parentObj = NetworkIdentity.spawned[parentID].gameObject;
spawner = parentObj.GetComponent<ObjectSpawner>();
spawner.obj = gameObject;
}
private void OnTriggerEnter(Collider other)
{
if (!isServer) return;
GameObject obj = other.gameObject;
Player player = obj.GetComponent<Player>();
if (player == null) return;
if(Apply(player)) spawner.Destroy();
}
public virtual bool Apply(Player p)
{
return false;
}
}
在ObjectSpawner.cs更新代码
using System.Collections;
using UnityEngine;
using Mirror;
public class ObjectSpawner : NetworkBehaviour
{
……
[Server]
public void Instantiate()
{
obj = Instantiate(prefab, transform.position, transform.rotation);
obj.GetComponent<Powerup>().parentID = GetComponent<NetworkIdentity>().netId;
NetworkServer.Spawn(obj);
}
……
}
35、生命恢复物品功能编写
新建PowerupHealth.cs,并添加代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerupHealth : Powerup
{
public int amount = 5;
public override bool Apply(Player p)
{
if (p.health == p.maxHealth) return false;
int value = p.health;
value += amount;
value = Mathf.Clamp(value, value, p.maxHealth);
p.health = value;
return true;
}
}
在Powerup.cs更新代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class Powerup : NetworkBehaviour
{
……
private void OnTriggerEnter(Collider other)
{
if (!isServer) return;
GameObject obj = other.gameObject;
Player player = obj.GetComponent<Player>();
if(Apply(player)) spawner.Destroy();
}
public virtual bool Apply(Player p)
{
return false;
}
}
36、盾牌UI的制作
将CircleEmpty贴图加入资源
在Player预制体中创建Shield画布
在Shield下创建Slider,并只保留fill
设置Slider
设置fill
测试
37、盾牌物品的功能实现
新建PowerupShield.cs,并添加代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerupShield : Powerup
{
public int amount = 3;
public override bool Apply(Player p)
{
if (p.shield == amount) return false;
p.shield = amount;
return true;
}
}
在Player.cs更新代码
using System;
using UnityEngine;
using UnityEngine.UI;
using Mirror;
public class Player : NetworkBehaviour
{
……
public Slider shieldSlider; // 护盾
……
[HideInInspector] [SyncVar(hook = nameof(OnShieldChange))] public int shield = 0;
……
[Server]
public void TankDamage(Bullet bullet)
{
if (shield > 0)
{
shield--; // 一炮的伤害为3,刚好把护盾抵消一格
return;
}
……
}
……
protected void OnShieldChange(int oldValue, int newValue)
{
shield = newValue;
shieldSlider.value = shield;
}
……
}