C# 当我的玩家死亡时,如何添加粒子系统?

C# 当我的玩家死亡时,如何添加粒子系统?,c#,unityscript,particle-system,C#,Unityscript,Particle System,我已经有一个死亡动画了。我想要一个粒子系统粒子开始与死亡动画。我有一个私有变量particleRed,我在awake函数中启动了它 我现在该怎么办 using UnityEngine; using System.Collections; using UnityStandardAssets.CrossPlatformInput; public class CharacterController2D : MonoBehaviour { // player c

我已经有一个死亡动画了。我想要一个粒子系统粒子开始与死亡动画。我有一个私有变量particleRed,我在awake函数中启动了它

我现在该怎么办

    using UnityEngine;
    using System.Collections;
    using UnityStandardAssets.CrossPlatformInput;

    public class CharacterController2D : MonoBehaviour {
    // player controls
    [Range(0.0f, 10.0f)] // create a slider in the editor and set limits on moveSpeed
    public float moveSpeed = 3f;

    public float jumpForce = 600f;

    // player health
    public int playerHealth = 1;

    // LayerMask to determine what is considered ground for the player
    public LayerMask whatIsGround;

    // Transform just below feet for checking if player is grounded
    public Transform groundCheck;

    // player can move?
    // we want this public so other scripts can access it but we don't want to show in editor as it might confuse designer
    [HideInInspector]
    public bool playerCanMove = true;

    // SFXs
    public AudioClip coinSFX;
    public AudioClip deathSFX;
    public AudioClip fallSFX;
    public AudioClip jumpSFX;
    public AudioClip victorySFX;


    // private variables below

    // store references to components on the gameObject
    Transform _transform;
    Rigidbody2D _rigidbody;
    Animator _animator;
    AudioSource _audio;
    ParticleSystem particleRed;

    // hold player motion in this timestep
    float _vx;
    float _vy;

    // player tracking
    bool facingRight = true;
    bool isGrounded = false;
    bool isRunning = false;
    bool _canDoubleJump = false;

    // store the layer the player is on (setup in Awake)
    int _playerLayer;

    // number of layer that Platforms are on (setup in Awake)
    int _platformLayer;

    void Awake () {
        // get a reference to the components we are going to be changing and store a reference for efficiency purposes
        _transform = GetComponent<Transform> ();

        _rigidbody = GetComponent<Rigidbody2D> ();
        if (_rigidbody==null) // if Rigidbody is missing
            Debug.LogError("Rigidbody2D component missing from this gameobject");

        _animator = GetComponent<Animator>();
        if (_animator==null) // if Animator is missing
            Debug.LogError("Animator component missing from this gameobject");

        _audio = GetComponent<AudioSource> ();
        if (_audio==null) { // if AudioSource is missing
            Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
            // let's just add the AudioSource component dynamically
            _audio = gameObject.AddComponent<AudioSource>();
        }
        particleRed = GetComponent<ParticleSystem>();

        // determine the player's specified layer
        _playerLayer = this.gameObject.layer;

        // determine the platform's specified layer
        _platformLayer = LayerMask.NameToLayer("Platform");
    }

    // this is where most of the player controller magic happens each game event loop
    void Update()
    {
        // exit update if player cannot move or game is paused
        if (!playerCanMove || (Time.timeScale == 0f))
            return;

        // determine horizontal velocity change based on the horizontal input
        _vx = CrossPlatformInputManager.GetAxisRaw ("Horizontal");

        // Determine if running based on the horizontal movement
        if (_vx != 0) 
        {
            isRunning = true;
        } else {
            isRunning = false;
        }

        // set the running animation state
        _animator.SetBool("Running", isRunning);

        // get the current vertical velocity from the rigidbody component
        _vy = _rigidbody.velocity.y;

        // Check to see if character is grounded by raycasting from the middle of the player
        // down to the groundCheck position and see if collected with gameobjects on the
        // whatIsGround layer
        isGrounded = Physics2D.Linecast(_transform.position, groundCheck.position, whatIsGround);  

        // Allow Double Jump after grounded
        if (isGrounded) 
        {
            _canDoubleJump = true;
        }
        // Set the grounded animation states
        _animator.SetBool("Grounded", isGrounded);

        if (isGrounded && CrossPlatformInputManager.GetButtonDown ("Jump")) { // If grounded AND jump button pressed, then allow the player to jump
            DoJump ();
        } else if (_canDoubleJump && CrossPlatformInputManager.GetButtonDown ("Jump")) 
        {
            DoJump();
            // double jumo can be possible once
            _canDoubleJump = false;
        }

        // If the player stops jumping mid jump and player is not yet falling
        // then set the vertical velocity to 0 (he will start to fall from gravity)
        if(CrossPlatformInputManager.GetButtonUp("Jump") && _vy>0f)
        {
            _vy = 0f;
        }

        // Change the actual velocity on the rigidbody
        _rigidbody.velocity = new Vector2(_vx * moveSpeed, _vy);

        // if moving up then don't collide with platform layer
        // this allows the player to jump up through things on the platform layer
        // NOTE: requires the platforms to be on a layer named "Platform"
        Physics2D.IgnoreLayerCollision(_playerLayer, _platformLayer, (_vy > 0.0f)); 

    }

    // Checking to see if the sprite should be flipped
    // this is done in LateUpdate since the Animator may override the localScale
    // this code will flip the player even if the animator is controlling scale
    void LateUpdate()
    {
        // get the current scale
        Vector3 localScale = _transform.localScale;

        if (_vx > 0) // moving right so face right
        {
            facingRight = true;
        } else if (_vx < 0) { // moving left so face left
            facingRight = false;
        }

        // check to see if scale x is right for the player
        // if not, multiple by -1 which is an easy way to flip a sprite
        if (((facingRight) && (localScale.x<0)) || ((!facingRight) && (localScale.x>0))) {
            localScale.x *= -1;
        }

        // update the scale
        _transform.localScale = localScale;
    }

    // if the player collides with a MovingPlatform, then make it a child of that platform
    // so it will go for a ride on the MovingPlatform
    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag=="MovingPlatform")
        {
            this.transform.parent = other.transform;
        }
    }

    // if the player exits a collision with a moving platform, then unchild it
    void OnCollisionExit2D(Collision2D other)
    {
        if (other.gameObject.tag=="MovingPlatform")
        {
            this.transform.parent = null;
        }
    }

    //make the player jump
    void DoJump()
    {
        // reset current vertical motion to 0 prior to jump
            _vy = 0f;
        // add a force in the up direction
        _rigidbody.AddForce (new Vector2 (0, jumpForce));
        // play the jump sound
        PlaySound(jumpSFX);
    }
    // do what needs to be done to freeze the player
    void FreezeMotion() {
        playerCanMove = false;
        _rigidbody.isKinematic = true;
    }

    // do what needs to be done to unfreeze the player
    void UnFreezeMotion() {
        playerCanMove = true;
        _rigidbody.isKinematic = false;
    }

    // play sound through the audiosource on the gameobject
    void PlaySound(AudioClip clip)
    {
        _audio.PlayOneShot(clip);
    }

    // public function to apply damage to the player
    public void ApplyDamage (int damage) {
        if (playerCanMove) {
            playerHealth -= damage;

            if (playerHealth <= 0) { // player is now dead, so start dying
                PlaySound(deathSFX);

                StartCoroutine (KillPlayer ());

            }
        }
    }

    // public function to kill the player when they have a fall death
    public void FallDeath () {
        if (playerCanMove) {
            playerHealth = 0;
            PlaySound(fallSFX);

            StartCoroutine (KillPlayer ());

        }

    }

    // coroutine to kill the player
    IEnumerator KillPlayer()
    {
        if (playerCanMove)
        {
            // freeze the player
            FreezeMotion();

            // play the death animation
            _animator.SetTrigger("Death");

            // After waiting tell the GameManager to reset the game
            yield return new WaitForSeconds(2.0f);

            if (GameManager.gm) // if the gameManager is available, tell it to reset the game
                GameManager.gm.ResetGame();
            else // otherwise, just reload the current level
                Application.LoadLevel(Application.loadedLevelName);
        }
    }

    public void CollectCoin(int amount) {
        PlaySound(coinSFX);

        if (GameManager.gm) // add the points through the game manager, if it is available
            GameManager.gm.AddPoints(amount);
    }

    // public function on victory over the level
    public void Victory() {
        PlaySound(victorySFX);
        FreezeMotion ();
        _animator.SetTrigger("Victory");

        if (GameManager.gm) // do the game manager level compete stuff, if it is available
            GameManager.gm.LevelCompete();
    }

    // public function to respawn the player at the appropriate location
    public void Respawn(Vector3 spawnloc) {
        UnFreezeMotion();
        playerHealth = 1;
        _transform.parent = null;
        _transform.position = spawnloc;
        _animator.SetTrigger("Respawn");
    }

    public void EnemyBounce ()
    {
        DoJump ();
    }
}
使用UnityEngine;
使用系统集合;
使用UnityStandardAssets.CrossPlatformInput;
公共类CharacterController2D:单行为{
//玩家控制
[范围(0.0f,10.0f)]//在编辑器中创建滑块并设置移动速度限制
公共浮动速度=3f;
公共浮子跳线力=600f;
//球员健康
公共int playerHealth=1;
//LayerMask,用于确定玩家的场地
公共层码头;
//在脚底下方变换,检查球员是否停飞
公开审查;
//玩家可以移动吗?
//我们想要这个公共的,以便其他脚本可以访问它,但我们不想在编辑器中显示,因为它可能会混淆设计器
[hideininstecpt]
public bool playerCanMove=true;
//SFXs
公共音频剪辑;
公共音频剪辑deathSFX;
公共音频剪辑;
公共音频剪辑跳线SFX;
公共音频剪辑胜利者;
//下面是私有变量
//存储对游戏对象上组件的引用
变换_变换;
刚体2d_刚体;
动画师;
音频源(AudioSource)音频;;
粒子系统粒子化;
//在此时间步中保持播放器运动
浮动vx;
浮球;
//球员跟踪
bool facingRight=正确;
bool isGrounded=false;
bool isRunning=false;
bool_canDoubleJump=false;
//存储播放器所在的图层(在唤醒模式下设置)
国际玩家层;
//平台所在的层数(在唤醒中设置)
int_平台层;
无效唤醒(){
//获取我们将要更改的组件的引用,并存储引用以提高效率
_transform=GetComponent();
_刚体=GetComponent();
if(_rigidbody==null)//如果缺少刚体
LogError(“此游戏对象缺少Rigidbody2D组件”);
_animator=GetComponent();
if(_animator==null)//如果缺少animator
LogError(“此游戏对象缺少动画组件”);
_audio=GetComponent();
如果(_audio==null){//如果缺少音频源
LogWarning(“此游戏对象缺少音频源组件。正在添加一个”);
//让我们动态添加AudioSource组件
_audio=gameObject.AddComponent();
}
particleRed=GetComponent();
//确定玩家指定的图层
_playerLayer=this.gameObject.layer;
//确定平台的指定层
_platformLayer=LayerMask.NameToLayer(“平台”);
}
//这是每个游戏事件循环中大部分玩家控制器魔法发生的地方
无效更新()
{
//如果玩家无法移动或游戏暂停,请退出更新
如果(!playerCanMove | |(Time.timeScale==0f))
返回;
//根据水平输入确定水平速度变化
_vx=CrossPlatformInputManager.GetAxisRaw(“水平”);
//确定是否根据水平运动进行跑步
如果(_vx!=0)
{
isRunning=true;
}否则{
isRunning=false;
}
//设置正在运行的动画状态
_animator.SetBool(“正在运行”,即正在运行);
//从刚体组件获取当前垂直速度
_vy=_刚体速度y;
//检查角色是否从玩家中间通过光线投射固定
//向下到地面检查位置,查看是否收集了游戏对象
//什么是底层
IsGround=Physics2D.Linecast(_transform.position、groundCheck.position、whatIsGround);
//接地后允许双跳
如果(接地)
{
_canDoubleJump=真;
}
//设置固定动画状态
_animator.SetBool(“接地”,isground);
如果(isGrounded&&CrossPlatformInputManager.GetButtonDown(“跳跃”){//如果按下了grounded和Jump按钮,则允许玩家跳跃
DoJump();
}else if(_canDoubleJump&&CrossPlatformInputManager.GetButtonDown(“Jump”))
{
DoJump();
//一次可以有两个jumo
_canDoubleJump=假;
}
//如果运动员中途停止跳跃,并且运动员还没有摔倒
//然后将垂直速度设置为0(他将开始从重力下降)
if(跨平台输入管理器.GetButtonUp(“跳转”)&&&&&U vy>0f)
{
_vy=0f;
}
//更改刚体上的实际速度
_刚体速度=新矢量2(_vx*移动速度,_vy);
//如果向上移动,则不要与平台层碰撞
//这允许玩家在平台层上跳转
//注意:要求平台位于名为“平台”的层上
物理2D.忽略层集合(_playerLayer,_platformLayer,(_vy>0.0f));
}
//检查精灵是否应该翻转
//这是在LateUpdate中完成的,因为动画师可能会覆盖localScale
//即使动画师正在控制缩放,此代码也将翻转播放器
void LateUpdate()
{
//获取当前刻度
Vector3 localScale=\u transform.localScale;
如果(_vx>0)//向右移动,则面向右侧
{
facingRight=正确;
}如果(_vx<0){//向左移动,则面向左
facingRight=错误;
}
//检查比例x是否适合玩家
//如果不是,则乘以-1,这是一种简单的计算f的方法
particleRed.enabled = true;