I've just started exploring unity & c# working together, and accidently I faced a next problem: I have a fish. Fish was supposed to go from left to right, then change its direction and go from right to left. I haven't finished that moving part yet, but I was going to do it with timer. So timer is active, fish starts to move, timer stops, changing direction, timer resets, fish starts to move etc. I want to flip my sprite, so it will face correct direction. It doesn't work from Elapsed function and I don't understand why. If you have any ideas, please share
using System.Timers;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FishBehavior : MonoBehaviour
{
public float moveSpeed;
private int direction; //for left -1, for right 1
private Timer timer;
private SpriteRenderer img;
private Rigidbody2D rb;
void Start()
{
img = GetComponent<SpriteRenderer>();
rb = GetComponent<Rigidbody2D>();
direction = 1;
timer = new Timer();
timer.Elapsed += TimerElapsed;
ChangeTimerOptions();
}
private void Move()
{
//moving
}
private void ChangeDirection()
{
direction *= -1;
img.flipX = !img.flipX; //Doesn't work!
//stop movement
}
private void ChangeTimerOptions()
{
System.Random rand = new System.Random();
timer.Interval = rand.Next(3000, 8000);
timer.Enabled = true;
Move();
}
private void TimerElapsed(object source, ElapsedEventArgs e)
{
ChangeDirection();
ChangeTimerOptions();
}
}