Unity C# 单例模式 学习复习笔记

Unity C# 单例模式 学习复习笔记

什么是单例模式:优缺,理解

Unity单例模式+例子_就一枚小白的博客-CSDN博客_unity 单例

学习链接:开关门   案例【Unity3D学习】Unity3D用单例模式实现简单交互功能、开关门 开关灯_哔哩哔哩_bilibili

单例脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sc03Singletion : MonoBehaviour
{

    //单例模式
    static Sc03Singletion instance;

    public static Sc03Singletion Instance()
    {

        if (instance==null)
        {
            instance = new Sc03Singletion();
        }

        return instance;
    }


    public void AnimBegin(GameObject obj,Animator ani,string state)
    {
        ani = obj.GetComponent<Animator>();

        if (ani.speed==0)
        {
            ani.speed = 1;
        }
        ani.SetBool(state,true);

    }

    public void AnimEnd(GameObject obj, Animator ani, string state)
    {
        if (ani.speed == 0)
        {
            return;
        }
        ani.SetBool(state, false);
    }

}

门开关脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sc03Door : MonoBehaviour
{
    Animator Ani_Door;
    string state;

    private void Start()
    {
        state = "OpenOrClose";
        Ani_Door = GetComponent<Animator>();
        Ani_Door.speed = 0;
    }


    public void OpenDoor()
    {
        //简单方法
        /* if (Ani_Door.speed==0)
         {
             Ani_Door.speed = 1;
         }
         Ani_Door.SetBool(state, true);*/


        //单例模式

        Sc03Singletion.Instance().AnimBegin(this.gameObject,Ani_Door,state);

    }

    public void CloseDoor()
    {
        /*
        if (Ani_Door.speed == 0)
        {
            return;
        }
        Ani_Door.SetBool(state, false);
        */

        Sc03Singletion.Instance().AnimEnd(this.gameObject, Ani_Door, state);

    }
}

灯控制脚本:

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sc03Light : MonoBehaviour
{
    Animator Ani_Light;
    string state;

    private void Start()
    {
        state = "lightOpenClose";
        Ani_Light = GetComponent<Animator>();
        Ani_Light.speed = 0;
    }



    public void LightOn()
    {
        Sc03Singletion.Instance().AnimBegin(this.gameObject, Ani_Light, state);
    }

    public void LightOff()
    {
        Sc03Singletion.Instance().AnimEnd(this.gameObject, Ani_Light, state);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Allen7474

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值