C#设计模式学习(沙盒模式)

控制类

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

public class TestSubclassSandbox : MonoBehaviour
{
    //A list that will store all superpowers(一个存储所有超能力的List)
    List<SuperPower> _superPowers = new List<SuperPower>();          //一个成员为基类的List用来调用类,把行为实例化!!

    private float _elapsedTime = 0.0f;

    void Start()
    {
        _superPowers.Add(new SkyLaunch());
        _superPowers.Add(new GroundDive());
        _superPowers.Add(new FlashSpeed());
        _elapsedTime = Time.realtimeSinceStartup;
    }

    void Update()
    {
        //Trigger once per second(每一秒触发一次)
        if (Time.realtimeSinceStartup - _elapsedTime > 1f)
        {
            for (int i = 0; i < _superPowers.Count; i++)
            {
                _superPowers[i].Activate();     //因为已经有实例化的对象了,调用对象里的成员函数
            }
            _elapsedTime = Time.realtimeSinceStartup;
        }

    }
}

基类

using UnityEngine;
using System.Collections;

//This is the base class(基类)
public abstract class SuperPower
{
    //Abstract interface for sub class(给子类提供的抽象接口)
    public abstract void Activate();
    
    //Some of the tool methods given to the child class(给子类提供的一些工具方法类)
    protected void Move(float speed)
    {
        Debug.Log("Moving with speed " + speed + "!(速度)");
    }

    protected void PlaySound(string coolSound)
    {
        Debug.Log("Playing sound " + coolSound+"!(音效)");
    }

    protected void SpawnParticles(string particles)
    {
        Debug.Log("Spawn Particles "+ particles+"!(粒子特效)");
    }
}

一个派生类

using UnityEngine;
using System.Collections;

//Subclasses
public class SkyLaunch : SuperPower
{
    //Has to have its own version of Activate()(子类实现自己版本的Activate()方法)
    public override void Activate()
    {
        Debug.Log("--------------------------SkyLaunch SuperPower Activate!--------------------");
        //make own unique features.(组合子类自己独特的功能)
        Move(10f);
        PlaySound("SkyLaunch");
        SpawnParticles("SkyLaunch Particles");
    }

转载自https://www.ctolib.com/Unity-Design-Pattern.html,写得真的是太好了,受益匪浅

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值