一、主要框架
二、项目需求
1.1版本
1.点击宝箱领取的金币钻石太拥挤,分散一点。
2.玩家金币钻石不够时没有相应处理。
1.2版本
1.与UI交互时不能发射子弹。
2.技能扣钻石太多。
3.boss撞击玩家数值变动一样且不是减少是增加。
1.3版本
1.boss撞击玩家当钻石金币不够时会产生负数。
2.炮台3太强,且钻石没用处,不削弱,只有氪金才可使用。
3.大鱼太多。
1.4版本
1.扑鱼是考虑了鱼的血量与子弹的伤害来模拟概率,这样玩家体验不好,要使用传统的概率来扑鱼。
2.炮台移动是根据鼠标的水平数值滑动来模拟跟随的,改为玩家按下ad键来旋转炮台。
2.0版本
1.增加新鱼。
2.增加浪潮功能。
3.切换场景。
三、C#关键脚本
1、Effect
Explosion
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 爆炸特效
///
public class Explosion : MonoBehaviour {
public float DestoryTime = 0.2f; //破坏时间
// Use this for initialization
void Start () {
Destroy(this.gameObject, DestoryTime);
}
// Update is called once per frame
void Update () {
transform.localScale +=new Vector3(Time.deltaTime*10, Time.deltaTime*10, Time.deltaTime*10) ; //尺寸由小变大
}
}
Pao
using UnityEngine;
using System.Collections;
public class Pao : MonoBehaviour {
///
/// 游戏中产生的泡泡
///
public int moveSpeed; //气泡移动速度
public bool isGamePao; //开关
// Use this for initialization
void Start () {
if (isGamePao)
{
moveSpeed = Random.Range(2, 4); //随机移动的速度
Destroy(this.gameObject, Random.Range(0.5f, 1f)); //破坏 摧毁 销毁的时间
}
else
{
moveSpeed = Random.Range(40, 100);
Destroy(this.gameObject, Random.Range(7f, 10f));
}
}
// Update is called once per frame
void Update () {
transform.Translate(-transform.right*moveSpeed*Time.deltaTime,Space.World); //围绕世界坐标旋转移动
}
}
Shake
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// boss攻击玩家产生的震动方法
///
public class Shake : MonoBehaviour {
private float cameraShake = 2; //摄像机震动系统
public GameObject UI; //红色被攻击ui
void Awake()
{
//gameObject.transform.localPosition = new Vector3(0,8.18f,0);
// gameObject.transform.localEulerAngles = new Vector3(90,0,180);
}
void Start () {
}
void Update () {
gameObject.transform.localPosition = new Vector3(0,28f, 0);
gameObject.transform.localEulerAngles = new Vector3(90, 0, 180);
if (Gun.Instance.bossAttack) //单例模式 boss被攻击
{
UI.SetActive(true); //红色背景的UI显示
transform.position = new Vector3((Random.Range(0f, cameraShake)) - cameraShake*0.5f, transform.position.y, transform.position.z); //震动X轴
transform.position = new Vector3(transform.position.x, transform.position.y, (Random.Range(0f, cameraShake)) - cameraShake * 0.5f); //震动Y轴
cameraShake = cameraShake / 1.05f;
if (cameraShake<0.05f)
{
//cameraShake小于0.5的时候直接归零
cameraShake = 0;
UI.SetActive(false);
Gun.Instance.bossAttack = false;
}
}
else
{
cameraShake = 5; //恢复震动系数
}
}
}
Shine
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
///
/// 星星闪耀的特效
///
public class Shine : MonoBehaviour {
private Image img; //闪耀的图片
public float speed=4; //闪耀的速度
private bool add; //开关
public void Awake()
{
img = GetComponent();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.forward * 4, Space.World); //旋转
if (!add)
{
img.color -= new Color(0, 0, 0, Time.deltaTime * speed); //透明度递减
if (img.color.a <=0.2f)
{
add = true;
}
}
else
{
img.color += new Color(0, 0, 0, Time.deltaTime * speed); //透明度递增
if (img.color.a >=0.8f)
{
add = false;
}
}
}
}
ShineHide
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
///
/// 隐藏显示闪耀UI的特效,比如枪,星星
///
public class ShineHide : MonoBehaviour {
private float timeVal = 0; //计时器
private bool isAdd = false; //开关
private Image img; //闪烁的图片
public float defineTime = 3; //自定义时间
void Awake()
{
img = GetComponent();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
timeVal += Time.deltaTime;
if (!isAdd)
{
img.color -= new Color(0, 0, 0, Time.deltaTime * 5); //颜色递减
if (timeVal > defineTime)
{
img.color = new Color(img.color.r, img.color.g, img.color.b, 0);
isAdd = true;
timeVal = 0;
}
}
else
{
img.color += new Color(0, 0, 0, Time.deltaTime * 5); //颜色递增
if (timeVal > defineTime)
{
img.color = new Color(img.color.r, img.color.g, img.color.b, 1);
isAdd = false;
timeVal = 0;
}
}
}
}
Water
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 水纹播放的特效
///
public class Water : MonoBehaviour {
//水波荡漾的效果
private SpriteRenderer sr;
public Sprite[] pictures;
private int count=0;
// Use this for initialization
void Start () {
sr = GetComponent();
}
// Update is called once per frame
void Update () {
sr.sprite = pictures[count];
count++;
if (count==pictures.Length)
{
count = 0;
}
}
}
2、Enemy
Boss
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
///
/// boss脚本
///
[Hotfix]
public class Boss : MonoBehaviour
{
public int hp = 50;//血量
public GameObject deadEeffect; //特效
public int GetGold = 10; //金币数量
public int GetDiamands = 10; //钻石
public GameObject diamands; //钻石预制体
public GameObject gold; //金币预制体
public float moveSpeed = 2;
protected int m_reduceGold; //减少的金币
protected int m_reduceDiamond;//减少钻石
protected Transform playerTransform; //玩家信息
protected GameObject fire; //火特效
protected GameObject ice; //冰特效
protected Animator iceAni; //冰动画
protected Animator gameObjectAni; //玩家动画
protected AudioSource bossAudio; //boss声效
//计时器
private float rotateTime; //旋转时间
private float timeVal;//计时器
protected bool hasIce; //是否冰封
protected bool isAttack; //是否攻击
[LuaCallCSharp]
void Start()
{
//持有引用赋值
fire = transform.Find("Fire").gameObject;
ice = transform.Find("Ice").gameObject;
iceAni = ice.transform.GetComponent();
gameObjectAni = GetComponent();
bossAudio = GetComponent();
playerTransform = Gun.Instance.transform;
m_reduceGold = 10; //应该为负数的 撞击时候减少 不是增加 用lua修复
m_reduceDiamond = 0;
}
// Update is called once per frame
void Update()
{
//冰冻效果
if (Gun.Instance.Ice)
{
gameObjectAni.enabled = false; //游戏本身动画状态机不能用
ice.SetActive(true);//冰封显示
if (!hasIce)
{
iceAni.SetTrigger("Ice"); //触发冰封的状态机
hasIce = true; //冰封
}
}
else
{
gameObjectAni.enabled = true;
hasIce = false;
ice.SetActive(false);
}
//灼烧效果
if (Gun.Instance.Fire)
{
fire.SetActive(true); //显示燃烧的对象
}
else
{
fire.SetActive(false); //隐藏燃烧的对象
}
if (Gun.Instance.Ice)
{
return;
}
//boss的行为方法
Attack(m_reduceGold, m_reduceDiamond); //执行递减的方法
if (!isAttack)
{
fishMove(); //没有被攻击的话 执行鱼移动的方法
}
}
///
/// 重写虚方法 虚方法 所有的子类都调用此方法
///
///
[LuaCallCSharp]
public virtual void TakeDamage(int attackValue)
{
if (Gun.Instance.Fire)
{
attackValue *= 2; //累乘伤害值
}
hp -= attackValue; //血量减少
if (hp <= 0)
{
Instantiate(deadEeffect, transform.position, transform.rotation); //当血量为0时候 实例化相关特效
Gun.Instance.GoldChange(GetGold * 10); //单例模式下的获取金币的方法
Gun.Instance.DiamandsChange(GetDiamands * 10);//单例模式下的获取钻石的方法
for (int i = 0; i < 11; i++)
{
GameObject itemGo = Instantiate(gold, transform.position, Quaternion.Euler(transform.eulerAngles + new Vector3(0, 18 + 36 * (i - 1), 0))); //实例化金币
itemGo.GetComponent().bossPrize = true; //执行boss的奖励
}
for (int i = 0; i < 11; i++)
{
GameObject itemGo = Instantiate(diamands, transform.position, Quaternion.Euler(transform.eulerAngles + new Vector3(0, 36 + 36 * (i - 1), 0))); //实例化钻石
itemGo.GetComponent().bossPrize = true;
}
Destroy(this.gameObject); //销毁本身
}
}
///
/// 鱼游动的方法
///
public void fishMove()
{
transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World); //鱼在世界坐标移动
if (rotateTime >= 5)
{
transform.Rotate(transform.forward * Random.Range(0, 361), Space.World); //随机旋转
rotateTime = 0;
}
else
{
rotateTime += Time.deltaTime; //时间递增
}
}
///
/// 攻击的方法
///
///
///
public void Attack(int reduceGold, int reduceDiamond)
{
if (timeVal > 20)
{
transform.LookAt(playerTransform); //朝向玩家的方向
transform.eulerAngles += new Vector3(90, -90, 0); //角度
isAttack = true;//是否攻击
timeVal = 0;
}
else
{
timeVal += Time.deltaTime;
}
if (isAttack)
{
gameObjectAni.SetBool("isAttack", true); //播放攻击的动画
transform.position = Vector3.Lerp(transform.position, playerTransform.position, 1 / Vector3.Distance(transform.position, playerTransform.position) * Time.deltaTime * moveSpeed); //差值运算
if (Vector3.Distance(transform.position, playerTransform.position) <= 4) //判断距离
{
if (reduceGold != 0)
{
Gun.Instance.GoldChange(reduceGold); //执行金币改变的方法
}
if (reduceDiamond != 0) //执行钻石改变的方法
{
Gun.Instance.DiamandsChange(reduceDiamond);
}
gameObjectAni.SetBool("isAttack", false);
isAttack = false;
Gun.Instance.BossAttack(); //boss攻击
rotateTime = 0;
Invoke("ReturnAngle", 4); //调用函数
}
}
}
///
/// 返回角度
///
public void ReturnAngle()
{
transform.eulerAngles = new Vector3(90, 0, 0);
}
}
CreateFish
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
///
/// 产鱼器
///
[Hotfix]
public class CreateFish : MonoBehaviour
{
//引用
public GameObject[] fishList;
public GameObject[] item;
public GameObject boss;
public GameObject boss2;
public GameObject boss3;
public Transform[] CreateFishPlace;
//关键点 持有关键脚本 否则运行都没有这脚本 报错 空方法
public HotFixScript hotFixScript;
private float ItemtimeVal = 0;//游戏物体计时器
private float createManyFish;
private float timeVals = 0;
//成员变量
private int num;
private int ItemNum;
private int placeNum;
private int CreateMorden;
//x:-26 - 26
//z:-16 - 16
private void Awake()
{
}
// Use this for initialization
void Start()
{
}
[LuaCallCSharp]
void Update()
{
//鱼群的生成
CreateALotOfFish();
//单种鱼的生成
if (ItemtimeVal >= 0.5)
{
//位置随机数
num = Random.Range(0, 4);
//游戏物体随机数
ItemNum = Random.Range(1, 101);
// Mathf.Floor(1.5f); //数学的方法 向下取整
//产生气泡
if (ItemNum < 20)
{
CreateGameObject(item[3]);
CreateGameObject(fishList[6]);
}
//贝壳10% 85-94
//第一种鱼42% 42
if (ItemNum <= 42)
{
CreateGameObject(fishList[0]);
CreateGameObject(item[0]);
CreateGameObject(fishList[3]);
CreateGameObject(item[0]);
}
//第二种鱼30% 43-72
else if (ItemNum >= 43 && ItemNum < 72)
{
CreateGameObject(fishList[1]);
CreateGameObject(item[0]);
CreateGameObject(fishList[4]);
}
//第三种鱼10% 73-84
else if (ItemNum >= 73 && ItemNum < 84)
{
CreateGameObject(fishList[2]);
CreateGameObject(fishList[5]);
}
//第一种美人鱼5%,第二种3% 95-98 99-100
else if (ItemNum >= 94 && ItemNum <= 98)
{
CreateGameObject(item[1]);
}
else if (ItemNum >= 84 && ItemNum < 86)
{
CreateGameObject(boss2);
}
else if (ItemNum > 98 && ItemNum < 100)
{
CreateGameObject(item[2]);
CreateGameObject(boss);
}
else
{
CreateGameObject(item[0]);
CreateGameObject(boss3);
}
ItemtimeVal = 0;
}
else
{
ItemtimeVal += Time.deltaTime;
}
}
//生成鱼群
private void CreateALotOfFish()
{
if (createManyFish >= 15)
{
if (CreateMorden == 2)
{
GameObject go = fishList[Random.Range(2, fishList.Length)];
for (int i = 0; i < 11; i++)
{
GameObject itemGo = Instantiate(go, transform.position, Quaternion.Euler(transform.eulerAngles + new Vector3(0, 45 * i, 0)));
itemGo.GetComponent().cantRotate = true;
}
createManyFish = 0;
}
else if (CreateMorden == 0 || CreateMorden == 1)
{
createManyFish += Time.deltaTime;
if (createManyFish >= 18)
{
createManyFish = 0;
}
if (timeVals >= 0.2f)
{
int num = Random.Range(0, 2);
GameObject itemGo = Instantiate(fishList[num], CreateFishPlace[placeNum].position + new Vector3(0, 0, Random.Range(-2, 2)), CreateFishPlace[placeNum].rotation);
itemGo.GetComponent().cantRotate = true;
timeVals = 0;
}
else
{
timeVals += Time.deltaTime;
}
}
}
else
{
createManyFish += Time.deltaTime;
placeNum = Random.Range(0, 2);
CreateMorden = Random.Range(0, 3);
}
}
private void CreateFishs(GameObject go)
{
Instantiate(go, RandomPos(num), Quaternion.Euler(go.transform.eulerAngles));
}
//产生游戏物体 创建鱼的游戏实例化
private void CreateGameObject(GameObject go)
{
if (go!=null)
{
Instantiate(go, RandomPos(num), Quaternion.Euler(RandomAngle(num) + go.transform.eulerAngles));
}
}
//随机位置
private Vector3 RandomPos(int num)
{
Vector3 Vpositon = new Vector3();
switch (num)
{
case 0:
Vpositon = new Vector3(-24, 1, Random.Range(-14f, 14f));//-30 - 30
break;
case 1:
Vpositon = new Vector3(Random.Range(-24f, 24f), 1, 14);//60 - 120
break;
case 2:
Vpositon = new Vector3(24, 1, Random.Range(-14f, 14f));//150-210
break;
case 3:
Vpositon = new Vector3(Random.Range(-24f, 24f), 1, -14);//-60- -120
break;
default:
break;
}
return Vpositon;
}
//随机角度
private Vector3 RandomAngle(int num)
{
Vector3 Vangle = new Vector3();
switch (num)
{
case 0:
Vangle = new Vector3(0, Random.Range(-30f, 30f), 0);//-30 - 30
break;
case 1:
Vangle = new Vector3(0, Random.Range(60f, 120f), 0);//60 - 120
break;
case 2:
Vangle = new Vector3(0, Random.Range(150f, 210f), 0);//150-210
break;
case 3:
Vangle = new Vector3(0, Random.Range(-60f, -120f), 0);//-60- -120
break;
default:
break;
}
return Vangle;
}
}
DeffendBoss
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
///
/// 有护盾的boss
///
[Hotfix]
public class DeffendBoss : Boss
{
private bool isDeffend = false; //开关
private float deffendTime = 0; //时间
public GameObject deffend; //确定有保护的对象
[LuaCallCSharp]
void Start()
{ //赋值
fire = transform.Find("Fire").gameObject;
ice = transform.Find("Ice").gameObject;
iceAni = ice.transform.GetComponent();
gameObjectAni = GetComponent();
bossAudio = GetComponent();
playerTransform = Gun.Instance.transform;
}
// Update is called once per frame
void Update()
{
//冰冻效果
if (Gun.Instance.Ice)
{
gameObjectAni.enabled = false;
ice.SetActive(true);
if (!hasIce)
{
iceAni.SetTrigger("Ice");
hasIce = true;
}
}
else
{
gameObjectAni.enabled = true;
hasIce = false;
ice.SetActive(false);
}
//灼烧效果
if (Gun.Instance.Fire)
{
fire.SetActive(true);
}
else
{
fire.SetActive(false);
}
if (Gun.Instance.Ice)
{
return;
}
//boss的行为方法
Attack(m_reduceGold, m_reduceDiamond);
if (!isAttack)
{
fishMove();
}
//保护方法
if (deffendTime >= 10)
{
deffendTime = 0;
DeffenMe();
}
else
{
deffendTime += Time.deltaTime;
}
}
///
/// 有防护功能
///
void DeffenMe()
{
isDeffend = true;
deffend.SetActive(true);
Invoke("CloseDeffendMe", 3); //3秒后 启用关闭防护罩的功能
}
private void CloseDeffendMe()
{
deffend.SetActive(false);
isDeffend = false;
}
///
/// 重写伤害的方法
///
///
public override void TakeDamage(int attackValue)
{
if (isDeffend)
{
return;
}
base.TakeDamage(attackValue);
}
}
Fish
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
///
/// 普通鱼的类
///
[Hotfix]
public class Fish : MonoBehaviour
{
//属性
public float moveSpeed = 2;
public int GetCold = 10;
public int GetDiamands = 10;
public int hp = 5;
//计时器
private float rotateTime;
private float timeVal;
//引用
public GameObject gold;
public GameObject diamands;
private GameObject fire;
private GameObject ice;
private Animator iceAni;
private Animator gameObjectAni;
private SpriteRenderer sr;
public GameObject pao;
//开关
private bool hasIce = false;
public bool isnet;
private bool isDead = false;
public bool cantRotate = false;
// Use this for initialization
void Start()
{
fire = transform.Find("Fire").gameObject;
ice = transform.Find("Ice").gameObject;
iceAni = ice.transform.GetComponent();
gameObjectAni = GetComponent();
sr = GetComponent();
Destroy(this.gameObject, 20);
}
void Update()
{
if (timeVal >= 14 || isDead)
{
sr.color -= new Color(0, 0, 0, Time.deltaTime);
}
else
{
timeVal += Time.deltaTime;
}
if (isDead)
{
return;
}
//冰冻效果
if (Gun.Instance.Ice)
{
gameObjectAni.enabled = false;
ice.SetActive(true);
if (!hasIce)
{
iceAni.SetTrigger("Ice");
hasIce = true;
}
}
else
{
gameObjectAni.enabled = true;
hasIce = false;
ice.SetActive(false);
}
//灼烧方法
if (Gun.Instance.Fire)
{
fire.SetActive(true);
}
else
{
fire.SetActive(false);
}
if (Gun.Instance.Ice)
{
return;
}
if (isnet)
{
Invoke("Net", 0.5f);
return;
}
fishMove();
}
///
/// 显示网的方法
///
public void Net()
{
if (isnet)
{
isnet = false;
}
}
///
/// 显示鱼游动的方法
///
public void fishMove()
{
transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
if (cantRotate)
{
return;
}
if (rotateTime >= 5)
{
transform.Rotate(transform.forward * Random.Range(0, 361), Space.World);
rotateTime = 0;
}
else
{
rotateTime += Time.deltaTime;
}
}
///
/// 鱼的受伤害情况 多大多捕 少打少捕 跟飞机大战差不多 但是这种做法捕鱼的概率玩家体验不好 应用传统的概率来捕 就算血量剩下10 打一下也可能捕到 打10下也不一定能捕到
///
/// 枪的火力值传递进来
[LuaCallCSharp]
public void TakeDamage(int attackValue)
{
if (Gun.Instance.Fire) //火焰效果 威力*2 gun 是单例模式 注意在lua实现的方法
{
attackValue *= 2;
}
hp -= attackValue;
if (hp <= 0)
{
isDead = true;
for (int i = 0; i < 9; i++)
{ //鱼被捕之后产生气泡
Instantiate(pao, transform.position, Quaternion.Euler(transform.eulerAngles + new Vector3(0, 45 * i, 0)));
}
gameObjectAni.SetTrigger("Die"); //播放动画 动画在lua实现的方法
Invoke("Prize", 0.7f); //调用奖励的方法 相当于协程的方法
}
}
///
/// 奖励的方法
///
private void Prize()
{
Gun.Instance.GoldChange(GetCold);
if (GetDiamands != 0)
{
Gun.Instance.DiamandsChange(GetDiamands);
Instantiate(diamands, transform.position, transform.rotation);
}
Instantiate(gold, transform.position, transform.rotation);
Destroy(this.gameObject);
}
}
InvisibleBoss
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
///
/// 会隐藏的boss
///
[Hotfix]
public class InvisibleBoss : Boss
{
private bool isInvisible = false; //是否可见
private float invisibleTime = 0;
private float recoverTime = 0;
private BoxCollider box; //碰撞器
private SpriteRenderer sr;
[LuaCallCSharp]
void Start()
{ //赋值
fire = transform.Find("Fire").gameObject;
ice = transform.Find("Ice").gameObject;
iceAni = ice.transform.GetComponent();
gameObjectAni = GetComponent();
box = GetComponent();
sr = GetComponent();
bossAudio = GetComponent();
playerTransform = Gun.Instance.transform;
}
// Update is called once per frame
void Update()
{
//冰冻效果
if (Gun.Instance.Ice)
{
gameObjectAni.enabled = false;
ice.SetActive(true);
if (!hasIce)
{
iceAni.SetTrigger("Ice");
hasIce = true;
}
}
else
{
gameObjectAni.enabled = true;
hasIce = false;
ice.SetActive(false);
}
//灼烧效果
if (Gun.Instance.Fire)
{
fire.SetActive(true);
}
else
{
fire.SetActive(false);
}
if (Gun.Instance.Ice)
{
return;
}
//boss的行为方法
Attack(m_reduceGold, m_reduceDiamond);
if (!isAttack)
{
fishMove();
}
//隐形方法
if (invisibleTime >= 10)
{
invisibleTime = 0;
Invisible();
}
else
{
invisibleTime += Time.deltaTime;
}
if (isInvisible)
{
sr.color -= new Color(0, 0, 0, Time.deltaTime);
box.enabled = false;
}
else
{
sr.color += new Color(0, 0, 0, Time.deltaTime);
if (recoverTime >= 3)
{
recoverTime = 0;
sr.color = new Color(sr.color.r, sr.color.g, sr.color.b, 1);
}
else
{
recoverTime += Time.deltaTime;
}
box.enabled = true;
}
}
///
/// 是否可见
///
private void Invisible()
{
isInvisible = true;
Invoke("CloseInvisible", 3); //3秒后关闭可见函数
}
///
/// 关闭可见函数
///
private void CloseInvisible()
{
isInvisible = false;
}
}
Qipao
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 挡子弹的气泡
///
public class Qipao : MonoBehaviour {
//属性
public float moveSpeed = 2;
//计时器
private float rotateTime;
// Use this for initialization
void Start()
{
Destroy(this.gameObject, 14); //15秒之后销毁
}
// Update is called once per frame
void Update()
{
fishMove(); //鱼游动的方法
}
public void fishMove()
{
transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
if (rotateTime >= 5)
{
transform.Rotate(transform.forward * Random.Range(0, 361), Space.World);
rotateTime = 0;
}
else
{
rotateTime += Time.deltaTime;
}
}
public void TakeDamage(int attackValue)
{
Destroy(this.gameObject);
}
}
3、Item
Card
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 铺到贝壳的道具卡
///
public class Card : MonoBehaviour {
private Transform playerTransform;
public int num;
public Sprite[] cards;
private SpriteRenderer sr;
private AudioSource audios;
// Use this for initialization
void Start () {
Destroy(this.gameObject,1);
audios = GetComponent();
sr = GetComponent();
sr.sprite = cards[num];
audios.Play();
}
// Update is called once per frame
void Update () {
}
}
FishNet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 渔网
///
public class FishNet : MonoBehaviour {
// Use this for initialization
void Start () {
Destroy(this.gameObject,0.2f);
}
// Update is called once per frame
void Update () {
//transform.Translate(-Vector3.up * moveSpeed * Time.deltaTime,Space.World);
}
///
/// 触发器事件
///
///
private void OnTriggerEnter(Collider other)
{
if (other.tag=="fish")
{
other.GetComponent().isnet = true;
}
}
}
Gold
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 金币,钻石
///
public class Gold : MonoBehaviour
{
///
/// 枚举类型
///
public enum ThePlaceTo
{
gold,
diamands,
imageGold,
imageDiamands
}
public ThePlaceTo thePlaceTo;
private Transform playerTransform;
public float moveSpeed = 3;
public GameObject star2;
private AudioSource audios;
public AudioClip goldAudio;
public AudioClip diamandsAudio;
private float timeVal2;
public float defineTime2;
private float timeBecome;
private float timeVal3;
public bool bossPrize = false;
private bool beginMove = false;
// Use this for initialization
private void Awake()
{
audios = GetComponent();
switch (thePlaceTo) //枚举类型的引用
{
case ThePlaceTo.gold:
playerTransform = Gun.Instance.goldPlace;
audios.clip = goldAudio;
break;
case ThePlaceTo.diamands:
playerTransform = Gun.Instance.diamondsPlace;
audios.clip = diamandsAudio;
break;
case ThePlaceTo.imageGold:
playerTransform = Gun.Instance.imageGoldPlace;
audios.clip = goldAudio;
break;
case ThePlaceTo.imageDiamands:
playerTransform = Gun.Instance.imageDiamandsPlace;
audios.clip = diamandsAudio;
break;
default:
break;
}
audios.Play();
}
void Start()
{
}
// Update is called once per frame
void Update()
{
if (timeBecome >= 0.5f)
{
beginMove = true;
}
else
{
timeBecome += Time.deltaTime;
}
if (beginMove)
{
transform.position = Vector3.Lerp(transform.position, playerTransform.position, 1 / Vector3.Distance(transform.position, playerTransform.position) * Time.deltaTime * moveSpeed);
if (thePlaceTo == ThePlaceTo.imageDiamands || thePlaceTo == ThePlaceTo.imageGold)
{
if (Vector3.Distance(transform.position, playerTransform.position) <= 2)
{
Destroy(this.gameObject);
}
return;
}
if (transform.position == playerTransform.position)
{
Destroy(this.gameObject);
}
timeVal2 = InistStar(timeVal2, defineTime2, star2);
}
else
{
transform.localScale += new Vector3(Time.deltaTime * 3, Time.deltaTime * 3, Time.deltaTime * 3);
if (bossPrize)
{
if (timeVal3 <= 0.3f)
{
timeVal3 += Time.deltaTime;
transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
}
}
}
}
///
/// 实例化星星
///
/// 计时器
/// 自定义次数
/// 星星
///
private float InistStar(float timeVals, float defineTimes, GameObject stars)
{
if (timeVals >= defineTimes)
{
Instantiate(stars, this.transform.position, Quaternion.Euler(this.transform.eulerAngles.x, this.transform.eulerAngles.y, this.transform.eulerAngles.z + Random.Range(-40f, 40f)));
timeVals = 0;
}
else
{
timeVals += Time.deltaTime;
}
return timeVals;
}
}
Missile
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 美人鱼
///
public class Missile : MonoBehaviour {
//属性
public int hp=15;
public int GetGold = 10;
public float moveSpeed=5;
//引用
public GameObject gold;
private GameObject fire;
private GameObject ice;
private Animator iceAni;
private Animator gameObjectAni;
public GameObject deadEeffect;
private SpriteRenderer sr;
//计时器
private float rotateTime;
//开关
private bool hasIce = false;
private float timeVal;
// Use this for initialization
void Start () {
fire = transform.Find("Fire").gameObject;
ice = transform.Find("Ice").gameObject;
iceAni = ice.transform.GetComponent();
gameObjectAni = GetComponent();
sr = GetComponent();
Destroy(this.gameObject, 8);
}
// Update is called once per frame
void Update () {
if (timeVal >= 7)
{
sr.color -= new Color(0, 0, 0, Time.deltaTime);
}
else
{
timeVal += Time.deltaTime;
}
//冰冻效果
if (Gun.Instance.Ice)
{
gameObjectAni.enabled = false;
ice.SetActive(true);
if (!hasIce)
{
iceAni.SetTrigger("Ice");
hasIce = true;
}
}
else
{
gameObjectAni.enabled = true;
hasIce = false;
ice.SetActive(false);
}
//灼烧效果
if (Gun.Instance.Fire)
{
fire.SetActive(true);
}
else
{
fire.SetActive(false);
}
if (Gun.Instance.Ice)
{
return;
}
transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
if (rotateTime >= 5)
{
transform.Rotate(transform.forward * Random.Range(0, 361), Space.World);
rotateTime = 0;
}
else
{
rotateTime += Time.deltaTime;
}
}
///
/// 美人鱼 获取幸运金币的方法
///
///
public void Lucky(int attckValue)
{
Gun.Instance.GoldChange(GetGold);
Instantiate(gold, transform.position, transform.rotation);
if (Gun.Instance.Fire)
{
attckValue *= 2;
}
hp -= attckValue;
if (hp<=0)
{
Instantiate(deadEeffect, transform.position, transform.rotation);
gameObjectAni.SetTrigger("Die");
Invoke("Prize", 0.7f);
}
}
///
/// 奖励
///
private void Prize()
{
Gun.Instance.GoldChange(GetGold * 10); //改变金币的方法
for (int i = 0; i < 5; i++)
{
Instantiate(gold, transform.position + new Vector3(-5f + i, 0, 0), transform.rotation);
}
Destroy(this.gameObject);
}
}
Shell
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 贝壳
///
public class Shell : MonoBehaviour {
//计时器
private float rotateTime;
private float timeVal = 0;//无敌状态计时器
//属性
public float moveSpeed = 5;
//开关
private bool isDeffend=true;
private bool hasIce = false;
//引用
public GameObject card;
private GameObject fire;
private GameObject ice;
private Animator iceAni;
private Animator gameObjectAni;
private SpriteRenderer sr;
private float timeVals;
// Use this for initialization
void Start () {
fire = transform.Find("Fire").gameObject;
ice = transform.Find("Ice").gameObject;
iceAni = ice.transform.GetComponent();
gameObjectAni = GetComponent();
sr = GetComponent();
Destroy(this.gameObject,10);
}
// Update is called once per frame
void Update () {
if (timeVals >= 9)
{
sr.color -= new Color(0, 0, 0, Time.deltaTime);
}
else
{
timeVals += Time.deltaTime;
}
//灼烧效果
if (Gun.Instance.Fire)
{
fire.SetActive(true);
}
else
{
fire.SetActive(false);
}
//冰冻效果
if (Gun.Instance.Ice)
{
gameObjectAni.enabled = false;
ice.SetActive(true);
if (!hasIce)
{
iceAni.SetTrigger("Ice");
hasIce = true;
}
}
else
{
gameObjectAni.enabled = true;
hasIce = false;
ice.SetActive(false);
}
if (Gun.Instance.Ice)
{
return;
}
transform.Translate(transform.right * moveSpeed * Time.deltaTime, Space.World);
if (rotateTime >= 5)
{
transform.Rotate(transform.forward * Random.Range(0, 361), Space.World);
rotateTime = 0;
}
else
{
rotateTime += Time.deltaTime;
}
if (timeVal<1)
{
timeVal += Time.deltaTime;
}
else if (timeVal>=1&&timeVal<1.5)
{
timeVal += Time.deltaTime;
isDeffend = false;
}
else if (timeVal>=1.5)
{
isDeffend = true;
timeVal = 0;
}
}
///
/// 获取特效
///
public void GetEffects()
{
if (isDeffend)
{
return;
}
else
{
int num = Random.Range(0, 3);
switch (num)
{
case 0:Gun.Instance.CanShootForFree();
break;
case 1:Gun.Instance.CanGetDoubleGold();
break;
case 2:Gun.Instance.CanShootNoCD();
break;
default:
break;
}
GameObject go= Instantiate(card, transform.position, card.transform.rotation) as GameObject;
go.GetComponent().num = num;
Destroy(this.gameObject);
}
}
}
4、Player
Bullect
using UnityEngine;
using System.Collections;
///
/// 散弹
///
public class Bullect : MonoBehaviour {
public GameObject explosions; //爆炸
public GameObject star;
public GameObject star1;
public GameObject star2;
public float moveSpeed; //移动速度
private float timeVal; //计时器
public float defineTime;
private float timeVal1;
public float defineTime1;
private float timeVal2;
public float defineTime2;
public Transform CreatePos; //创建位置
public GameObject net;
public int level;
public float attackValue;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
timeVal=InistStar(timeVal,defineTime,star);
timeVal1=InistStar(timeVal1,defineTime1,star1);
timeVal2=InistStar(timeVal2,defineTime2,star2);
transform.Translate(transform.up*moveSpeed*Time.deltaTime,Space.World);
}
///
/// 实例化星星
///
/// 计时器
/// 自定义次数
/// 星星游戏对象
///
private float InistStar(float timeVals,float defineTimes,GameObject stars)
{
if (timeVals>=defineTimes) {
Instantiate(stars, CreatePos.transform.position, Quaternion.Euler(CreatePos.transform.eulerAngles.x, CreatePos.transform.eulerAngles.y, CreatePos.transform.eulerAngles.z+Random.Range(-40f,40f)));
timeVals=0;
}
else {
timeVals+=Time.deltaTime;
}
return timeVals;
}
///
/// 触发器
///
///
private void OnTriggerEnter(Collider other)
{
if (other.tag == "fish" || other.tag == "boss")
{
other.SendMessage("TakeDamage", attackValue);
GameObject go = Instantiate(net, transform.position + new Vector3(0, 1, 0), transform.rotation);
go.transform.localScale = new Vector3(level, level, level);
Instantiate(explosions, transform.position, transform.rotation);
Destroy(this.gameObject);
}
else if (other.tag == "missile")
{
other.SendMessage("Lucky", attackValue);
GameObject go = Instantiate(net, transform.position + new Vector3(0, 1, 0), transform.rotation);
go.transform.localScale = new Vector3(level, level, level);
Instantiate(explosions, transform.position, transform.rotation);
Destroy(this.gameObject);
}
else if (other.tag == "Shell")
{
other.SendMessage("GetEffects");
GameObject go = Instantiate(net, transform.position + new Vector3(0, 1, 0), transform.rotation);
go.transform.localScale = new Vector3(level, level, level);
Instantiate(explosions, transform.position, transform.rotation);
Destroy(this.gameObject);
}
else if (other.tag == "Qipao")
{
GameObject go = Instantiate(net, transform.position + new Vector3(0, 1, 0), transform.rotation);
go.transform.localScale = new Vector3(level, level, level);
Instantiate(explosions, transform.position, transform.rotation);
Destroy(this.gameObject);
}
/*else*/
if (other.tag == "Wall")
{
float angleValue = Vector3.Angle(transform.up, other.transform.up);
if (angleValue < 90)
{
transform.eulerAngles += new Vector3(0, 0, 2*angleValue);
}
else if (Vector3.Angle(transform.up, other.transform.up) > 90)
{
transform.eulerAngles -= new Vector3(0, 0, 360-2 * angleValue);
}
else
{
transform.eulerAngles += new Vector3(0, 0, 180);
}
}
}
}
Gun
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua; //引用命名空间
///
/// 枪
///
[Hotfix] //打上标签
public class Gun : MonoBehaviour
{
//属性
public int gold = 100;
public int diamands = 50;
public int gunLevel = 1;
private float rotateSpeed = 5f;
public float attackCD = 1;
private float GunCD = 4;
public int level = 1;
//引用
public AudioClip[] bullectAudios;
private AudioSource bullectAudio;
public Transform attackPos;
public GameObject[] Bullects;
public GameObject net;
public GunChange[] gunChange;
public Transform goldPlace;
public Transform diamondsPlace;
public Transform imageGoldPlace;
public Transform imageDiamandsPlace;
//文本
public Text goldText;
public Text diamandsText;
//开关
private bool canShootForFree = false;
private bool canGetDoubleGold = false;
public bool canShootNoCD = false;
public bool canChangeGun = true;
public bool bossAttack = false;
public bool Fire = false;
public bool Ice = false;
public bool Butterfly = false;
public bool attack = false;
//切换音乐
public bool changeAudio;
///
/// 单例模式
///
private static Gun instance;
public static Gun Instance
{
get
{
return instance;
}
set
{
instance = value;
}
}
private void Awake()
{
instance = this;
gold = 1000;
diamands = 1000;
level = 2;
bullectAudio = GetComponent();
}
// Use this for initialization
void Start()
{
// UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(); //是否触碰到UI;
}
// Update is called once per frame
void Update()
{
goldText.text = gold.ToString();
diamandsText.text = diamands.ToString();
//旋转枪的方法
RotateGun();
if (GunCD <= 0)
{
canChangeGun = true;
GunCD = 4;
}
else
{
GunCD -= Time.deltaTime;
}
//攻击的方法
if (canShootNoCD)
{
Attack();
attack = true;
return;
}
if (attackCD >= 1 - gunLevel * 0.3)
{
Attack();
attack = true;
}
else
{
attackCD += Time.deltaTime;
}
}
///
/// 以下是方法的定义
///
//旋转枪
[LuaCallCSharp]
private void RotateGun()
{
float h = Input.GetAxisRaw("Mouse Y");
float v = Input.GetAxisRaw("Mouse X");
//旋转枪的关键api
transform.Rotate(-Vector3.forward * v * rotateSpeed);
transform.Rotate(Vector3.forward * h * rotateSpeed);
ClampAngle();
//245,115
}
//换枪的方法
public void UpGun()
{
gunLevel += 1;
if (gunLevel == 4)
{
gunLevel = 1;
}
gunChange[0].ToGray();
gunChange[1].ToGray();
canChangeGun = false;
}
public void DownGun()
{
gunLevel -= 1;
if (gunLevel == 0)
{
gunLevel = 3;
}
gunChange[0].ToGray();
gunChange[1].ToGray();
canChangeGun = false;
}
//限制角度 旋转枪的角度
private void ClampAngle()
{
float y = transform.eulerAngles.y;
if (y <= 35)
{
y = 35;
}
else if (y >= 150)
{
y = 150;
}
transform.eulerAngles = new Vector3(transform.eulerAngles.x, y, transform.eulerAngles.z);
}
//攻击方法
[LuaCallCSharp] //在需要更改的地方打上此标签
private void Attack()
{
if (Input.GetMouseButtonDown(0))
{
bullectAudio.clip = bullectAudios[gunLevel - 1];
bullectAudio.Play();
if (Butterfly)
{
Instantiate(Bullects[gunLevel - 1], attackPos.position, attackPos.rotation * Quaternion.Euler(0, 0, 20));
Instantiate(Bullects[gunLevel - 1], attackPos.position, attackPos.rotation * Quaternion.Euler(0, 0, -20));
}
Instantiate(Bullects[gunLevel - 1], attackPos.position, attackPos.rotation);
if (!canShootForFree)
{
GoldChange(-1 - (gunLevel - 1) * 2);
}
attackCD = 0;
attack = false;
}
}
//增减金钱
[LuaCallCSharp]
public void GoldChange(int number)
{
if (canGetDoubleGold)
{
if (number > 0)
{
number *= 2;
}
}
gold += number;
}
//增减钻石
[LuaCallCSharp]
public void DiamandsChange(int number)
{
diamands += number;
}
///
/// 贝壳触发的一些效果方法
///
public void CanShootForFree()
{
canShootForFree = true;
Invoke("CantShootForFree", 5);
}
public void CantShootForFree()
{
canShootForFree = false;
}
public void CanGetDoubleGold()
{
canGetDoubleGold = true;
Invoke("CantGetDoubleGold", 5);
}
public void CantGetDoubleGold()
{
canGetDoubleGold = false;
}
public void CanShootNoCD()
{
canShootNoCD = true;
Invoke("CantShootNoCD", 5);
}
public void CantShootNoCD()
{
canShootNoCD = false;
}
//boss攻击的方法
public void BossAttack()
{
bossAttack = true;
}
}
GunChange
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
///
/// 切枪的按钮
///
public class GunChange : MonoBehaviour
{
public bool add;
private Button button;
private Image image;
public Sprite[] buttonSprites;//0.+ 1.灰色的+ 2.- 3.灰色的-
// Use this for initialization
void Start()
{
//赋值
button = transform.GetComponent
ButterFly
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua;
///
/// 散弹按钮
///
[Hotfix]
public class ButterFly : MonoBehaviour
{
Button but;
private float timeVal = 15;
private bool canUse = true;
private float totalTime = 15;
public GameObject uiView;
public Slider cdSlider;
private int reduceDiamands;
private void Awake()
{
but = transform.GetComponent
Fire
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua;
///
/// 灼烧 特效的方法
///
[Hotfix]
public class Fire : MonoBehaviour
{
private Button but;
private float timeVal = 15;
private bool canUse = true;
private float totalTime = 15;
public Slider cdSlider;
private int reduceDiamands;
private void Awake()
{
//给按钮添加事件监听
but = transform.GetComponent
GunImage
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua;
///
/// 负责UI显示的枪
///
[Hotfix]
public class GunImage : MonoBehaviour
{
public Sprite[] Guns;
private Image img;
public Transform idlePos;
public Transform attackPos;
private float rotateSpeed = 5f;
private void Awake()
{
img = transform.GetComponent();
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
//旋转枪的方法
RotateGun();
img.sprite = Guns[Gun.Instance.gunLevel - 1];
//攻击的方法
if (Gun.Instance.attack)
{
if (Input.GetMouseButtonDown(0))
{
attack();
}
}
}
///
/// 攻击的时候往前位置移动
///
private void attack()
{
transform.position = Vector3.Lerp(transform.position, attackPos.position, 0.5f);
Invoke("idle", 0.4f);
}
///
/// 停止攻击时候往后移动
///
private void idle()
{
transform.position = Vector3.Lerp(transform.position, idlePos.position, 0.2f);
}
//旋转枪
[LuaCallCSharp]
private void RotateGun()
{
float h = Input.GetAxisRaw("Mouse Y");
float v = Input.GetAxisRaw("Mouse X");
transform.Rotate(-Vector3.forward * v * rotateSpeed);
transform.Rotate(Vector3.forward * h * rotateSpeed);
ClampAngle();
}
//限制角度
private void ClampAngle()
{
float z = transform.eulerAngles.z;
if (z <= 35)
{
z = 35;
}
else if (z >= 150)
{
z = 150;
}
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, z);
}
}
Ice
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua;
///
/// 冰冻
///
[Hotfix]
public class Ice : MonoBehaviour
{
private float timeVal = 10;
private bool canUse = true;
public Slider cdSlider;
private float totalTime = 10;
Button but;
private AudioSource fireAudio;
private int reduceDiamands;
// Use this for initialization
private void Awake()
{
but = transform.GetComponent
CreatePao
using UnityEngine;
using System.Collections;
///
/// 产生UI泡泡
///
public class CreatePao : MonoBehaviour
{
public GameObject pao;
public Transform panel;
private float timeVal = 6;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (timeVal >= 6)
{
for (int i = 0; i < 4; i++)
{
Invoke("InstPao", 1);
}
timeVal = 0;
}
else
{
timeVal += Time.deltaTime;
}
}
private void InstPao()
{
GameObject itemGo = Instantiate(pao, transform.position, Quaternion.Euler(0, 0, Random.Range(-80, 0))) as GameObject;
itemGo.transform.SetParent(panel);
}
}
Ground
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 地图背景
///
public class Ground : MonoBehaviour
{
private MeshRenderer mr;
public Material[] materialList;
private AudioSource audioSource;
public AudioClip[] audioClips;
// Use this for initialization
void Start()
{
mr = GetComponent();
audioSource = GetComponent();
}
// Update is called once per frame
void Update()
{
if (Gun.Instance.changeAudio)
{
audioSource.clip = audioClips[Gun.Instance.level - 1];
audioSource.Play();
Gun.Instance.changeAudio = false;
}
if (Gun.Instance.level == 1)
{
if (Gun.Instance.Fire)
{
mr.material = materialList[1];
}
else if (Gun.Instance.Ice)
{
mr.material = materialList[2];
}
else
{
mr.material = materialList[0];
}
}
else if (Gun.Instance.level == 2)
{
if (Gun.Instance.Fire)
{
mr.material = materialList[4];
}
else if (Gun.Instance.Ice)
{
mr.material = materialList[5];
}
else
{
mr.material = materialList[3];
}
}
else if (Gun.Instance.level == 3)
{
if (Gun.Instance.Fire)
{
mr.material = materialList[7];
}
else if (Gun.Instance.Ice)
{
mr.material = materialList[8];
}
else
{
mr.material = materialList[6];
}
}
}
}
LoadGame
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.Networking; //引入命名空间
using System.IO; //文件操作
///
/// 加载游戏的空场景
///
public class LoadGame : MonoBehaviour {
public Slider processView;
// Use this for initialization
void Start () {
LoadGameMethod();
}
// Update is called once per frame
void Update () {
}
///
/// 加载游戏
///
public void LoadGameMethod()
{
StartCoroutine(LoadResourceCototine());//加载热更新脚本的协程函数
StartCoroutine(StartLoading_4(2)); //加载场景
}
///
/// 异步加载
///
///
///
private IEnumerator StartLoading_4(int scene)
{
int displayProgress = 0;
int toProgress = 0;
AsyncOperation op = SceneManager.LoadSceneAsync(scene);
op.allowSceneActivation = false;
while (op.progress < 0.9f)
{
toProgress = (int)op.progress * 100;
while (displayProgress < toProgress)
{
++displayProgress;
SetLoadingPercentage(displayProgress);
yield return new WaitForEndOfFrame();
}
}
toProgress = 100;
while (displayProgress < toProgress)
{
++displayProgress;
SetLoadingPercentage(displayProgress);
yield return new WaitForEndOfFrame();
}
op.allowSceneActivation = true;
}
///
/// 修复脚本的关键方法
///
///
IEnumerator LoadResourceCototine() {
//鱼的主要脚本
UnityWebRequest request = UnityWebRequest.Get(@"http://ota25v09k.bkt.clouddn.com/fish.lua.txt"); //文本地址
yield return request.SendWebRequest(); //发送完之后把相关的文本存起来
string str = request.downloadHandler.text;//得到的文本存起来
//File.WriteAllText(@"E:\2018\7\0717\FishingJoy001\UnityPackageManager\fish.lua.txt",str); //调用文件的静态方法存到指定的位置 有的话就覆盖 没有就创建
File.WriteAllText(Application.persistentDataPath+@"/fish.lua.txt", str);
//鱼的释放脚本
UnityWebRequest request1 = UnityWebRequest.Get(@"http://ota25v09k.bkt.clouddn.com/fishDispose.lua.txt"); //获取网络请求地址
yield return request1.SendWebRequest(); //发送网络请求
string str1 = request1.downloadHandler.text; //下载下来以文本的形式请求
// File.WriteAllText(@"E:\2018\7\0717\FishingJoy001\UnityPackageManager\fishDispose.lua.txt",str1); //对文件或者字符串进行写入操作
File.WriteAllText(Application.persistentDataPath+@"/fishDispose.lua.txt", str1);
//引用命名空间
UnityWebRequest request2 = UnityWebRequest.Get(@"http://ota25v09k.bkt.clouddn.com/util.lua.txt"); //获取网络请求地址
yield return request2.SendWebRequest(); //发送网络请求
string str2 = request2.downloadHandler.text; //下载下来以文本的形式请求
// File.WriteAllText(@"E:\2018\7\0717\FishingJoy001\UnityPackageManager\fishDispose.lua.txt",str1); //对文件或者字符串进行写入操作
File.WriteAllText(Application.persistentDataPath + @"/util.lua.txt", str2);
}
private void SetLoadingPercentage(float v)
{
processView.value = v / 100;
}
}
Mylight
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Mylight : MonoBehaviour {
public Sprite[] lights;
private Image img;
private int i;
private float timeVal;
private void Awake()
{
img = GetComponent();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (timeVal>=0.08f)
{
img.sprite = lights[i];
i++;
if (i == lights.Length)
{
i = 0;
}
timeVal = 0;
}
else
{
timeVal += Time.deltaTime;
}
}
}
ReturnMain
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ReturnMain : MonoBehaviour {
private Button but;
// Use this for initialization
void Start()
{
but = GetComponent
Star
using UnityEngine;
using System.Collections;
public class Star : MonoBehaviour {
public float moveSpeed=1;
// Use this for initialization
void Start () {
Destroy(gameObject,Random.Range(0.4f,1));
}
// Update is called once per frame
void Update () {
//transform.Translate(-transform.right*moveSpeed*Time.deltaTime,Space.World);
}
}
StartGame
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class StartGame : MonoBehaviour {
private Button but;
// Use this for initialization
void Start () {
but = GetComponent
Treasour
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua;
///
/// 宝藏
///
[Hotfix]
public class Treasour : MonoBehaviour
{
private Button but;
private Image img;
public GameObject gold;
public GameObject diamands;
public GameObject cdView;
public Transform cavas;
private bool isDrease;
private void Awake()
{
but = GetComponent
四、Xlua关键脚本
HotFixScript
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System.IO;
using UnityEngine.Networking;
public class HotFixScript : MonoBehaviour {
//定义虚拟环境
private LuaEnv luaEnv;
//定义一个字典 用来存贮名称 预制体
public static Dictionary prefabDict = new Dictionary();
void Awake() {
luaEnv = new LuaEnv(); //赋值
luaEnv.AddLoader(MyLoader);
luaEnv.DoString("require'fish'");
}
///
/// 注意与lua的平级关系 一般写在awake方法中
///
void Start () {
//luaEnv = new LuaEnv(); //赋值
//luaEnv.AddLoader(MyLoader);
//luaEnv.DoString("require'fish'");
}
void Update () {
// Debug.Log ( request.downloadProgress);
}
private byte[] MyLoader(ref string filePath) {
// string absPath = @"E:\2018\7\0717\FishingJoy001\UnityPackageManager\"+filePath+".lua.txt"; //注意格式
string absPath = Application.persistentDataPath+@"/" + filePath + ".lua.txt";
return System.Text.Encoding.UTF8.GetBytes( File.ReadAllText(absPath));
}
///
/// 脚本生命周期
///
void OnDisable() {
luaEnv.DoString("require'fishDispose'");
}
///
/// 释放lua环境
///
private void OnDestroy() {
luaEnv.Dispose();
}
///
/// 加载ab包
///
//public void LoadABTest() {
// //加载ab包
// // AssetBundle ab = AssetBundle.LoadFromFile("文件路径");
// AssetBundle ab = AssetBundle.LoadFromFile("");
// //加载完之后用gameobject去接收它
// // GameObject go = ab.LoadAsset("资源名称(预制体名称)");
// GameObject go = ab.LoadAsset("");
//}
///
/// 加载资源的方法
///
// [LuaCallCSharp]
// public static void LoadResources(string resName,string filePath) {
//加载ab包 第一种方式 本地文件夹 静态方法
//AssetBundle ab = AssetBundle.LoadFromFile(@"E:\2018\7\0716\FishingJoy001\AssetBundles\" + filePath);
//实例化出来
//GameObject gameObject = ab.LoadAsset(resName);
//存入字典
//prefabDict.Add(resName,gameObject);
//加载ab包 第二种方式 网络加载
// }
[LuaCallCSharp]
public void LoadResources(string resName, string filePath) //去掉静态关键词 static
{
//开始协程来加载
StartCoroutine(LoadResourceCorotine(resName,filePath));
}
///
/// 开启协程加载
///
///
// UnityWebRequest request;
IEnumerator LoadResourceCorotine(string resName,string filePath) {
// request = UnityWebRequest.GetAssetBundle(@"http://ota25v09k.bkt.clouddn.com/" + filePath);
UnityWebRequest request = UnityWebRequest.GetAssetBundle(@"http://ota25v09k.bkt.clouddn.com/" + filePath);
yield return request.SendWebRequest();
//if (request.isNetworkError||request.isHttpError)
//{
// Debug.Log(request.error);
//}
//else
//{
// AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request); --api手册方式
AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
GameObject gameObject = ab.LoadAsset(resName);
prefabDict.Add(resName,gameObject);
// }
}
///
/// 从字典中获取游戏物体
///
///
[LuaCallCSharp]
public static GameObject GetGameObject(string goName) {
if (prefabDict.ContainsKey(goName)==false)
{
return null;
}
return prefabDict[goName];
}
}
HotFixEmpty
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
///
/// 定义一个空类 方便以后实现
///
[Hotfix]
public class HotFixEmpty : MonoBehaviour {
void Start () {
}
void Update () {
}
///
/// 海浪触发器
///
///
void OnTriggerEnter(Collider coll) {
}
///
/// 自身实现的一些类 比如海浪类 以及一些其他要实现的类 留有余地 方面下次实现
///
void MonoBehaviourMethod() {
}
}
fish.lua
--print("HelloWorld123!");
--1.1 点击宝箱领取的金币钻石太拥挤,分散一点。 更换位置 注意 进行注入操作
UnityEngine=CS.UnityEngine;
xlua.hotfix(CS.Treasour,'CreatePrize',function(self)
for i=0,4,1 do
--local go=CS.UnityEngine.GameObject.Instantiate(self.gold,self.transform.position+CS.UnityEngine.Vector3(-10+i*40,0,0),self.transform.rotation);
local go=UnityEngine.GameObject.Instantiate(self.gold,self.transform.position+UnityEngine.Vector3(-10+i*40,0,0),self.transform.rotation);
go.transform.SetParent(go.transform,self.cavas);
local go1=UnityEngine.GameObject.Instantiate(self.diamands,self.transform.position+UnityEngine.Vector3(0,40,0)+UnityEngine.Vector3(-10+i*40,0,0),self.transform.rotation);
go1.transform.SetParent(go1.transform,self.cavas);
end
end)
--1.1 玩家金币钻石不够时没有相应处理。 注意格式
xlua.private_accessible(CS.Gun); --访问私有变量的关键语句
xlua.hotfix(CS.Gun,'Attack',function(self)
if UnityEngine.Input.GetMouseButtonDown(0) then
--1.2 与UI交互时不能发射子弹。
if UnityEngine.EventSystems.EventSystem.current:IsPointerOverGameObject() then --注意不是静态方法 是普通方法 用冒号:
return;
end
--金币不够时作出相应处理 否则还是可以发射
--[[if self.gold<1+(self.gunLevel-1)*2 or gold==0 then
return;
end
]]--
--1.3 炮台3太强,且钻石没用处,不削弱,只有技能才消耗。 意思就是 炮台3也要消耗钻石
if self.gunLevel==3 and self.diamands<3 then --如果枪的等级等于3或者钻石小于3的时候 条件不满足返回
return;
elseif self.gunLevel~=3 then --枪的火力不等于3等级的时候 做如下判断
if self.gold<1+(self.gunLevel-1)*2 or gold==0 then --金币小于火力消耗的数量或者等于0时候返回
return;
end
end
self.bullectAudio.clip=self.bullectAudios[self.gunLevel-1];
self.bullectAudio:Play(); --注意普通方法是继承关系
if self.Butterfly then
UnityEngine.GameObject.Instantiate(self.Bullects[self.gunLevel-1],self.attackPos.position,self.attackPos.rotation*UnityEngine.Quaternion.Euler(0,0,20));
UnityEngine.GameObject.Instantiate(self.Bullects[self.gunLevel-1],self.attackPos.position,self.attackPos.rotation*UnityEngine.Quaternion.Euler(0,0,-20));
end
UnityEngine.GameObject.Instantiate(self.Bullects[self.gunLevel-1],self.attackPos.position,self.attackPos.rotation);
--如果不是免费射击 即扣除金币火钻石
if not self.canShootForFree then
if self.gunLevel==3 then
self:DiamandsChange(-3);
else
self:GoldChange(-1-(self.gunLevel-1)*2);
end
end
self.attackCD=0;
self.attack=false;
end
end)
--*************************************************************
--1.2技能扣钻石太多。 修改初始变量 让他变小点
xlua.private_accessible(CS.Fire);
xlua.hotfix(CS.Fire,'Start',function(self)
self.reduceDiamands = 8;
end);
xlua.private_accessible(CS.Ice);
xlua.hotfix(CS.Ice,'Start',function(self)
self.reduceDiamands = 8;
end);
xlua.private_accessible(CS.ButterFly);
xlua.hotfix(CS.ButterFly,'Start',function(self)
self.reduceDiamands=5;
end);
--*************************************************************
--1.2 boss撞击玩家数值变动一样且不是减少是增加。 意思就是方法里面有其他语句 只是改其中的一句语句或者增加些关键语句
local util =require 'util'; --引用命名空间
--第一类boss
xlua.private_accessible(CS.Boss);
util.hotfix_ex(CS.Boss,'Start',function(self)
self.Start(self); --先执行自身的方法
self.m_reduceGold=self.m_reduceGold-20; --再改变值
end);
--第二类boss
xlua.private_accessible(CS.DeffendBoss);
util.hotfix_ex(CS.DeffendBoss,'Start',function(self)
self.Start(self); --先执行自身的方法
self.m_reduceGold=self.m_reduceGold-30; --再改变值
end);
--第三类boss
xlua.private_accessible(CS.InvisibleBoss);
util.hotfix_ex(CS.InvisibleBoss,'Start',function(self)
self.Start(self); --先执行自身的方法
self.m_reduceDiamond=self.m_reduceDiamond-5; --再改变值 这个是改变钻石 不是金币
end);
--*************************************************************
--1.3 boss撞击玩家当钻石金币不够时会产生负数。 是不能产生负数的
--xlua.private_accessible(CS.Gun); --上面已经写过了,可以访问私有变量的关键词 这里不再写了·
util.hotfix_ex(CS.Gun,'GoldChange',function(self,number) --大鱼碰撞玩家时候金币减少的方法
self.GoldChange(self,number); --先执行自身的方法
if self.gold<-number then --负数再取 负就是 正数
self.gold=0; --归零
return; --返回
end
end)
--xlua.private_accessible(CS.Gun); --访问私有变量的关键词
util.hotfix_ex(CS.Gun,'DiamandsChange',function(self,number)
self.DiamandsChange(self,number); --先执行自身的方法
if self.diamands<-number then
self.diamands=0; --重置 返回
return;
end
end);
--1.3 大鱼太多。
local canCreateNewFish=true; --2.0 判断海浪碰到不能产生新鱼
local changeMapTimeval=0;
xlua.hotfix(CS.CreateFish,'Start',function(self) --2.0 增加鱼的方式 一种新鱼
--CS.HotFixScript.LoadResources('level3fish3','gameobject\\enemy.ab'); --这是静态的方法 点 加载新鱼
--CS.HotFixScript.LoadResources('SeaWave','gameobject\\wave.ab'); --参数1: 预制体名称 参数2: 打包的文件名称 注意区分
self.hotFixScript:LoadResources('level3fish3','enemy.ab'); --注意是把脚本挂在自身上 还引用挂相机的脚本 HotFixScript上
self.hotFixScript:LoadResources('SeaWave','wave.ab');
end);
xlua.private_accessible(CS.CreateFish); --访问私有变量
--util.hotfix_ex(CS.CreateFish,'Update',function(self) --执行自身方法再执行修改的方法
xlua.hotfix(CS.CreateFish,'Update',function(self) --这个是update的方法
--2.0 生成海浪
if canCreateNewFish then
if changeMapTimeval>=20 then --好浪产生时间 5秒
go=CS.HotFixScript.GetGameObject('SeaWave');--获取预制体
UnityEngine.GameObject.Instantiate(go); --实力化
canCreateNewFish=false; --不能产生新鱼
changeMapTimeval=0;--计时器归零
elseif changeMapTimeval<60 then
changeMapTimeval=changeMapTimeval+UnityEngine.Time.deltaTime;
end
else
return; --不能产生新鱼的话 直接返回
end
--普通方法是用冒号 : 静态类 C#自带的静态方法用点 . 切记
self:CreateALotOfFish(); --产生鱼群 普通方法用冒号 继承
--单种鱼的生成
if self.ItemtimeVal >= 0.5 then
--位置随机数 Random按下F12跟踪静态方法
self.num =UnityEngine.Mathf.Floor(UnityEngine.Random.Range(0, 4));
--打印下这随机数
--print(self.num);
--print(UnityEngine.Random.Range(0,4)); --两个方法重载float int
--游戏物体随机数
self.ItemNum =UnityEngine.Mathf.Floor(UnityEngine.Random.Range(1, 101));
--申请鱼的长度局部变量 把长度劈成一半
local halfLength=self.fishList.Length/2;
local littlefishTypeIndex=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(0,halfLength)); --小鱼随机的数
local bigfishTypeIndex=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(halfLength,self.fishList.Length)); --大鱼的随机数
local itemTypeIndex=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(0,self.item.Length)); --物品随机数 贝壳类
--产生气泡
if self.ItemNum < 20 then
self:CreateGameObject(self.item[3]);
--self:CreateGameObject(self.fishList[6]);
end
--贝壳10% 85-94
--第一种鱼42% 42
if self.ItemNum <= 42 then
--[[ self:CreateGameObject(fishList[0]);
self:CreateGameObject(item[0]);
self:CreateGameObject(fishList[3]);
self:CreateGameObject(item[0]);--]]
--产生3种小鱼 随机产生的小鱼
for i=0,2,1 do
self:CreateGameObject(self.fishList[littlefishTypeIndex]);
end
--产生道具
self:CreateGameObject(self.item[itemTypeIndex]);
--第二种鱼30% 43-72
elseif self.ItemNum >= 43 and self.ItemNum < 72 then
for i=0,1,1 do
self:CreateGameObject(self.fishList[bigfishTypeIndex]);
end
self:CreateGameObject(self.item[itemTypeIndex]);
--[[self:CreateGameObject(fishList[1]);
self:CreateGameObject(item[0]);
self:CreateGameObject(fishList[4]);--]]
--第三种鱼10% 73-84 这种概率用来产生新鱼
--[[elseif self.ItemNum >= 73 and self.ItemNum < 84 then
self:CreateGameObject(fishList[2]);
self:CreateGameObject(fishList[5]);
--]]
--2.0 增加新鱼。73 - 84
elseif self.ItemNum>=73 and self.ItemNum<84 then
newFish=CS.HotFixScript.GetGameObject('level3fish3'); --静态方法 点 获取新鱼的方法
--if newFish~=nil then
self:CreateGameObject(newFish); --调用创建鱼的方法
--end
elseif self.ItemNum>=84 and self.ItemNum<86 then --产生第二种鱼
self:CreateGameObject(self.boss); --注意boss类型
--第一种美人鱼5%,第二种3% 95-98 99-100
elseif self.ItemNum >= 87 and self.ItemNum <= 88 then
self:CreateGameObject(self.boss2); --产生的概率比较小
elseif self.ItemNum==100 then
self:CreateGameObject(self.boss3);
--[[elseif self.ItemNum > 98 and self.ItemNum < 100 then
self:CreateGameObject(self.item[2]);
self:CreateGameObject(self.boss);
--]]
else
self:CreateGameObject(self.item[0]);
--self:CreateGameObject(boss3);
end
self.ItemtimeVal = 0; --注意时间归零的位置
else
self.ItemtimeVal =CS.UnityEngine.Time.deltaTime+self.ItemtimeVal; --时间相加 跟之前++不一样
end
end);
--****************************************************************
--1.4 扑鱼是考虑了鱼的血量与子弹的伤害来模拟概率,这样玩家体验不好,要使用传统的概率来扑鱼。
xlua.private_accessible(CS.Fish); --访问私有变量的脚本
xlua.hotfix(CS.Fish,'TakeDamage',function(self,attackValue)
if CS.Gun.Instance.Fire then --火焰效果 威力*2 注意单例实现的效果
--self.attackValue = self.attackValue*2; --传递的参数不用加self的
attackValue=attackValue*2;
end
-- self.hp = self.attackValue - self.hp; --不用递减 随机数来递减 这样更能模拟现实中的情况
local catchValue=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(0,100));--随机捕捉值,调用数学的方法向下取整
if catchValue <= (50-(self.hp-attackValue))/2 then --注意设计的公式 血量越高捕捉的概率越小 血量越小捕捉的概率越大 随机出来的值作比较 50是一般的概率 生命血量 伤害值 /2 拼概率
self.isDead = true;
for i = 0,8,1 do
--鱼被捕之后产生气泡
UnityEngine.GameObject.Instantiate(self.pao, self.transform.position, UnityEngine.Quaternion.Euler(self.transform.eulerAngles + UnityEngine.Vector3(0, 45 * i, 0)));
end
self.gameObjectAni:SetTrigger("Die"); --播放动画 lua 调用普通方法用冒号 静态方法用点 注意这点
self:Invoke("Prize", 0.7); --调用奖励的方法 注意区分普通方法和静态方法 没有浮点类型 把‘f’删除
end
end);
--重写boss方法
xlua.hotfix(CS.Boss,'TakeDamage',function(self,attackValue) --传入的参数不带self
if CS.Gun.Instance.Fire then --主要单例实现的方法
attackValue =attackValue* 2; --累乘伤害值
end
-- self.hp = attackValue-self.hp; --血量减少
local catchValue=UnityEngine.Mathf.Floor(UnityEngine.Random.Range(0,100));
--if catchValue<=(50-(self.hp-attackValue))/2 then
if catchValue<=(attackValue*3-self.hp)/10 then --注意设计的公式
UnityEngine.GameObjet.Instantiate(self.deadEeffect, self.transform.position, self.transform.rotation); --当血量为0时候 实例化相关特效
CS.Gun.Instance:GoldChange(self.GetGold * 10); --单例模式下的获取金币的方法 这是单例的普通方法 是冒号 不是点
CS.Gun.Instance:DiamandsChange(self.GetDiamands * 10);--单例模式下的获取钻石的方法
for i = 0,10,1 do
local itemGo = UnityEngine.GameObject.Instantiate(self.gold, self.transform.position, UnityEngine.Quaternion.Euler(self.transform.eulerAngles + UnityEngine.Vector3(0, 18 + 36 * (i - 1), 0))); --实例化金币
itemGo:GetComponent('Gold').bossPrize = true; --执行boss的奖励 跟普通奖励不一样 先发散开来 注意lua执行的语法不一样 没有泛型 获取组件或者脚本用冒号
end
for i = 0 , 10,1 do
local itemGo1 =UnityEngine.GameObject.Instantiate(self.diamands, self.transform.position, UnityEngine.Quaternion.Euler(self.transform.eulerAngles + UnityEngine.Vector3(0, 36 + 36 * (i - 1), 0))); --实例化钻石
itemGo1:GetComponent('Gold').bossPrize = true; --获取同一个脚本Gold 用冒号
end
UnityEngine.Object.Destroy(self.gameObject); --销毁本身 静态的方法 命名空间下的类 用的是 点 可以省去Object?
end
end);
--1.4 炮台移动是根据鼠标的水平数值滑动来模拟跟随的,改为玩家按下ad键来旋转炮台。
--xlua.private_accessible(CS.Gun);
--[[xlua.hotfix(CS.Gun,'RotateGun',function(self) --虚拟枪
if UnityEngine.Input.GetKey(UnityEngine.KeyCode.A) then --注意枚举的实现方法 unity自带的加CS.UnityEngine 其他 CS.脚本名.枚举
self.transform:Rotate(UnityEngine.Vector3.forward*self.rotateSpeed); --注意旋转是普通方法 用的是冒号 按下F12跟踪一下
elseif UnityEngine.Input.GetKey(UnityEngine.KeyCode.D) then
self.transform:Rotate(-UnityEngine.Vector3.forward*self.rotateSpeed); --注意方向的取反
end
self:ClampAngle(); --调用限制角度的方法
end);
xlua.private_accessible(CS.GunImage); --访问私有的方法
xlua.hotfix(CS.GunImage,'RotateGun',function(self) --实体枪的旋转 方法
if UnityEngine.Input.GetKey(UnityEngine.KeyCode.A) then
self.transform:Rotate(UnityEngine.Vector3.forward*self.rotateSpeed);
elseif UnityEngine.Input.GetKey(UnityEngine.KeyCode.D) then
self.transform:Rotate(-UnityEngine.Vector3.forward*self.rotateSpeed);
end
self:ClampAngle(); --调用限制角度的方法
end);
--]]
-- 2.0 增加浪潮功能。 整个类都要修复 不用加[LuacallCsharp] 这个类是挂在海浪上的
xlua.private_accessible(CS.HotFixEmpty); --访问私有的方法
xlua.hotfix(CS.HotFixEmpty,'Start',function(self) --开始方法
self:Invoke("MonoBehaviourMethod",8);
end);
xlua.hotfix(CS.HotFixEmpty,'Update',function(self) --更新方法
self.transform:Translate(-self.transform.right*2.5*UnityEngine.Time.deltaTime,UnityEngine.Space.World); --向下边慢慢移动
end);
xlua.hotfix(CS.HotFixEmpty,'OnTriggerEnter',function(self,coll) --触发器 如果碰到有便签的 都要销毁 除了四堵墙之外
if coll.tag~="Untagged" and coll.tag~="Wall" then
UnityEngine.Object.Destroy(coll.gameObject);
end
end);
--重写海浪类的方法
xlua.hotfix(CS.HotFixEmpty,'MonoBehaviourMethod',function(self) --海浪方法
CS.Gun.Instance.level=CS.Gun.Instance.level+1; --调用此方法等级加1;
if CS.Gun.Instance.level==4 then --等级到达4的时候 恢复到等级1
CS.Gun.Instance.level=1;
end
canCreateNewFish=true; --可以生成新鱼
CS.Gun.Instance.changeAudio=true; --切换 背景声效
UnityEngine.Object.Destroy(self.gameObject,3); --销毁自身
end);
fishDispose.lua
--置空 否则暂停会报错
xlua.hotfix(CS.Treasour,'CreatePrize',nil);
xlua.hotfix(CS.Gun,'Attack',nil);
xlua.hotfix(CS.Fire,'Start',nil);
xlua.hotfix(CS.Ice,'Start',nil);
xlua.hotfix(CS.ButterFly,'Start',nil);
--改关键语句 xlua一样也要置空
xlua.hotfix(CS.Boss,'Start',nil);
xlua.hotfix(CS.DeffendBoss,'Start',nil);
xlua.hotfix(CS.InvisibleBoss,'Start',nil);
--1.3 反注册
xlua.hotfix(CS.Gun,'GoldChange',nil);
xlua.hotfix(CS.Gun,'DiamandsChange',nil);
xlua.hotfix(CS.CreateFish,'Update',nil);
--1.4
xlua.hotfix(CS.Fish,'TakeDamage',nil);
xlua.hotfix(CS.Boss,'TakeDamage',nil);
xlua.hotfix(CS.Gun,'RotateGun',nil);
xlua.hotfix(CS.GunImage,'RotateGun',nil);
--2.0
xlua.hotfix(CS.CreateFish,'Start',nil);
xlua.hotfix(CS.HotFixEmpty,'Start',nil);
xlua.hotfix(CS.HotFixEmpty,'Update',nil);
xlua.hotfix(CS.HotFixEmpty,'OnTriggerEnter',nil) ;
xlua.hotfix(CS.HotFixEmpty,'MonoBehaviourMethod',nil) ;
util.lua
-- Tencent is pleased to support the open source community by making xLua available.
-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
-- http://opensource.org/licenses/MIT
-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
local unpack = unpack or table.unpack
local function async_to_sync(async_func, callback_pos)
return function(...)
local _co = coroutine.running() or error ('this function must be run in coroutine')
local rets
local waiting = false
local function cb_func(...)
if waiting then
assert(coroutine.resume(_co, ...))
else
rets = {...}
end
end
local params = {...}
table.insert(params, callback_pos or (#params + 1), cb_func)
async_func(unpack(params))
if rets == nil then
waiting = true
rets = {coroutine.yield()}
end
return unpack(rets)
end
end
local function coroutine_call(func)
return function(...)
local co = coroutine.create(func)
assert(coroutine.resume(co, ...))
end
end
local move_end = {}
local generator_mt = {
__index = {
MoveNext = function(self)
self.Current = self.co()
if self.Current == move_end then
self.Current = nil
return false
else
return true
end
end;
Reset = function(self)
self.co = coroutine.wrap(self.w_func)
end
}
}
local function cs_generator(func)
local generator = setmetatable({
w_func = function()
func()
return move_end
end
}, generator_mt)
generator:Reset()
return generator
end
local function loadpackage(...)
for _, loader in ipairs(package.searchers) do
local func = loader(...)
if type(func) == 'function' then
return func
end
end
end
local function auto_id_map()
local hotfix_id_map = require 'hotfix_id_map'
local org_hotfix = xlua.hotfix
xlua.hotfix = function(cs, field, func)
local map_info_of_type = hotfix_id_map[typeof(cs):ToString()]
if map_info_of_type then
if func == nil then func = false end
local tbl = (type(field) == 'table') and field or {[field] = func}
for k, v in pairs(tbl) do
local map_info_of_methods = map_info_of_type[k]
local f = type(v) == 'function' and v or nil
for _, id in ipairs(map_info_of_methods or {}) do
CS.XLua.HotfixDelegateBridge.Set(id, f)
end
--CS.XLua.HotfixDelegateBridge.Set(
end
else
return org_hotfix(cs, field, func)
end
end
end
--和xlua.hotfix的区别是:这个可以调用原来的函数
local function hotfix_ex(cs, field, func)
assert(type(field) == 'string' and type(func) == 'function', 'invalid argument: #2 string needed, #3 function needed!')
local function func_after(...)
xlua.hotfix(cs, field, nil)
local ret = {func(...)}
xlua.hotfix(cs, field, func_after)
return unpack(ret)
end
xlua.hotfix(cs, field, func_after)
end
local function bind(func, obj)
return function(...)
return func(obj, ...)
end
end
--为了兼容luajit,lua53版本直接用|操作符即可
local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor
local enum_or_op_ex = function(first, ...)
for _, e in ipairs({...}) do
first = enum_or_op(first, e)
end
return first
end
-- description: 直接用C#函数创建delegate
local function createdelegate(delegate_cls, obj, impl_cls, method_name, parameter_type_list)
local flag = enum_or_op_ex(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.NonPublic,
CS.System.Reflection.BindingFlags.Instance, CS.System.Reflection.BindingFlags.Static)
local m = parameter_type_list and typeof(impl_cls):GetMethod(method_name, flag, nil, parameter_type_list, nil)
or typeof(impl_cls):GetMethod(method_name, flag)
return CS.System.Delegate.CreateDelegate(typeof(delegate_cls), obj, m)
end
return {
async_to_sync = async_to_sync,
coroutine_call = coroutine_call,
cs_generator = cs_generator,
loadpackage = loadpackage,
auto_id_map = auto_id_map,
hotfix_ex = hotfix_ex,
bind = bind,
createdelegate = createdelegate,
}