I would like to ask how to trigger an action or function after some time. In my case, I have a function class timer which shows in below as FuntiontTimer.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FuncTime
{
private Action action;
private float timer;
private bool isDestroyed;
public FuncTime(Action action, float timer)
{
this.action = action;
this.timer = timer;
isDestroyed = false;
}
public void Update()
{
if (!isDestroyed) {
timer -= Time.deltaTime;
if (timer < 0)
{
action();
DestroySelf();
}
}
}
private void DestroySelf()
{
isDestroyed = true;
}
}
The code works fine while I test with testing.cs below with MonoBehaviour
public class Testing : MonoBehaviour
{
private FuncTime funcTimer;
private void Start()
{
funcTimer = new FuncTime(Action, 3f);
}
private void Update()
{
funcTimer.Update();
}
private void Action()
{
Debug.Log("Testing!");
}
}
But then, when I put to code below, is not working. I would to have cameraShake active after 30f from time where I start.
public class CameraShaker : MonoBehaviour
{
public float power = 0.7f;
public float duration = 1.0f;
public Transform camera;
public float slowDownNo;
public bool shaking;
Vector3 startPosition;
float initialDuration;
void Start()
{
camera = Camera.main.transform;
startPosition = camera.localPosition;
initialDuration = duration;
}
// Update is called once per frame
void Update()
{
if (shaking)
{
if(duration > 0)
{
camera.localPosition = startPosition + Random.insideUnitSphere * power;
duration -= Time.deltaTime * slowDownNo;
} else
{
shaking = false; //time can be placed here
duration = initialDuration;
camera.localPosition = startPosition;
}
}
}
}