Unity问题从GameObject Enemy中的另一个脚本激活相机中带有参数的功能

Unity problem activating a function with parameters in camera from another script in GameObject Enemy

我有一个脚本,可以通过放置一个按钮让相机摇晃,因为 这是一个 public 访问函数,如果我在放置按钮时这样做,它会很好地工作,但我无法实现的是调用该函数,以便每次我的玩家与敌人碰撞时他都会摇晃。我希望你能帮助我。

相机抖动代码为:

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

public class ScreenShaker : MonoBehaviour {

    private float shakeAmount = 0.5f;

    private float shakeTime = 0.0f;
    private Vector3 initialPosition;
    private bool isScreenShaking = false;

    void Update () {
        if(shakeTime > 0)
        {
            this.transform.position = Random.insideUnitSphere * shakeAmount + initialPosition;
            shakeTime -= Time.deltaTime;
        }
        else if(isScreenShaking)
        {
            isScreenShaking = false;
            shakeTime = 0.0f;
            this.transform.position = initialPosition;
        }
    }

    public void ScreenShakeForTime(float time)
    {
        initialPosition = this.transform.position;
        shakeTime = time;
        isScreenShaking = true;
    }
}

敌人代码是:

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

    public class ControladorEnemigoCirculoMediano : MonoBehaviour
    {
        void OnTriggerEnter2D(Collider2D other)
        {
            if (other.tag == "Player") 
            {
            Here I don't know what to call the public void function ScreenShakeForTime (float time); 
            I already tried many things online but when my character comes into contact with the character, I don't do the shake in the camera.
            }
        }
    }

你能告诉我敌人游戏对象碰撞器 isTrigger 是否启用 如果未启用,则使用 OnColliderEnter2D(Collision2D other){} 进行碰撞检测

您可以在 ScreenShaker class 中创建 Unity-singleton,例如:

class ScreenShaker
{
  public static ScreenShaker Instance {private set; get;};

  void Awake() {
    Instance = this;
  }
}

而且比从任何地方打电话都好:

ScreenShaker.Instance.ScreenShakeForTime(2f);

这是最简单的方法,但创建标准单例可能更好(由您决定)。 而且不要忘记在 OnDestroy()

上销毁它