XNA, Draw Angle on sprite animation - c#

Recently I have changed my code from being a non-animated sprite to being animated. Now I'm having some trouble with the angle of the image.
When I turn I can see that the angle works because the fireballs are shooting in the correct direction, but the animated sprite is not. I have tried using base.Angle in the SpriteBatch.Draw method but it didn't take 5 arguments.
This is my code:
class Dragon : MovingGameObj
{
public Dragon()
{
framerate = 14;
timetolive = 3000;
repeat = 1;
timer = 0;
framesX = 1;
framesY = 2;
frameSize = 100;
alive = true;
activeframe = 0;
MaxSpeed = 2.5F;
FireballPower = 0;
prevKs = Keyboard.GetState();
prevKs2 = Keyboard.GetState();
Life = 100F;
Kills = 0;
Angle = -(float)(Math.PI / 2);
}
public bool alive;
private int activeframe;
int tmpTid = 0;
public int framerate { set; get; }
public int timetolive { set; get; }
public int repeat { set; get; }
public int framesX { set; get; }
public int framesY { set; get; }
public int timer { set; get; }
public int frameSize { set; get; }
public bool Enemy { get; set; }
public float MaxSpeed { get; set; }
public float FireballPower { get; set; }
public int WeaponType { get; set; }
public bool FireballFired { get; set; }
public float Life { get; set; }
public int Kills { get; set; }
protected KeyboardState prevKs;
protected KeyboardState prevKs2;
public void Respawn()
{
Life = 100F;
Random randomerare = new Random();
Position = new Vector2(randomerare.Next(1000), randomerare.Next(1000));
Angle = 0F;
}
public override void Update(GameTime gameTime)
{
KeyboardState ks = Keyboard.GetState();
KeyboardState ks2 = Keyboard.GetState();
#region Player 1
if (Enemy == false)
{
if (ks.IsKeyDown(Keys.Up))
{
if (Speed < 0) Speed = 0;
if (Speed < MaxSpeed) Speed = Speed * 1.005F + 0.01F;
else Speed = MaxSpeed;
}
if (ks.IsKeyDown(Keys.Down))
{
if (Speed > -1.0F) Speed -= 0.04F;
else Speed = -1.0F;
}
if (ks.IsKeyUp(Keys.Down) && ks.IsKeyUp(Keys.Up) && Speed > 0)
{
Speed -= 0.01F;
if (Speed <= 0) Speed = 0;
}
if (ks.IsKeyUp(Keys.Down) && ks.IsKeyUp(Keys.Up) && Speed < 0)
{
Speed += 0.01F;
if (Speed >= 0) Speed = 0;
}
if (ks.IsKeyUp(Keys.Left))
{
Angle += 0.02F;
}
if (ks.IsKeyUp(Keys.Right))
{
Angle -= 0.02F;
}
if (ks.IsKeyDown(Keys.Space))
{
if (FireballPower < 100)
FireballPower += 0.5F;
else
FireballPower = 100;
}
if (ks.IsKeyUp(Keys.Space) && prevKs.IsKeyDown(Keys.Space))
{
//FireballPower = 0;
FireballFired = true;
}
}
#endregion
#region Player 2
if (Enemy == true)
{
if (ks2.IsKeyDown(Keys.W))
{
if (Speed < 0) Speed = 0;
if (Speed < MaxSpeed) Speed = Speed * 1.005F + 0.01F;
else Speed = MaxSpeed;
}
if (ks2.IsKeyDown(Keys.S))
{
if (Speed > -1.0F) Speed -= 0.04F;
else Speed = -1.0F;
}
if (ks2.IsKeyUp(Keys.S) && ks2.IsKeyUp(Keys.W) && Speed > 0)
{
Speed -= 0.01F;
if (Speed <= 0) Speed = 0;
}
if (ks2.IsKeyUp(Keys.S) && ks2.IsKeyUp(Keys.W) && Speed < 0)
{
Speed += 0.01F;
if (Speed >= 0) Speed = 0;
}
if (ks2.IsKeyUp(Keys.A))
{
Angle += 0.02F;
}
if (ks2.IsKeyUp(Keys.D))
{
Angle -= 0.02F;
}
if (ks2.IsKeyDown(Keys.LeftControl))
{
if (FireballPower < 100)
FireballPower += 0.5F;
else
FireballPower = 100;
}
if (ks2.IsKeyUp(Keys.LeftControl) && prevKs2.IsKeyDown(Keys.LeftControl))
{
//FireballPower = 0;
FireballFired = true;
}
}
#endregion
prevKs = ks;
prevKs2 = ks2;
Direction = new Vector2((float)Math.Cos(Angle), (float)Math.Sin(Angle));
timer += gameTime.ElapsedGameTime.Milliseconds;
if (timer > timetolive)
{
alive = false;
}
tmpTid += gameTime.ElapsedGameTime.Milliseconds;
if (tmpTid > (1000 / framerate))
{
activeframe += 1;
tmpTid = 0;
if (activeframe > (framesX * framesY))
{
activeframe = 0;
}
}
base.Update(gameTime);
}
public override void Draw(SpriteBatch spriteBatch)
{
Rectangle tmp = new Rectangle(activeframe%framesX*frameSize,activeframe/framesY*frameSize,frameSize,frameSize);
spriteBatch.Draw(base.Gfx,base.Position, tmp,Color.White);
}
}

Try using this SpriteBatch.Draw() overload:
spriteBatch.Draw(base.Gfx, base.Position, tmp, Color.White, Angle, Vector2.Zero, 1f, SpriteEffects.None, 0f);

Related

Pyramiding system for Ctrader?

Max open trades
Hi, guys.. I have to modify a bot to set a maximum trades of whatever number I give it.
At the moment it opens max one trade but I want to be able to tell the bot to have 3 open trades at the same time, for example...
Is there a way to do it?
CODE BELOW!
using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(AccessRights = AccessRights.None)]
public class ThreeBarInsideBar : Robot
{
int upClose;
int upCloseBefore;
int insideBar;
int downClose;
int downCloseBefore;
int counter =0;
Position position;
[Parameter(DefaultValue = 10000)]
public int Volume { get; set; }
[Parameter("Stop Loss (pips)", DefaultValue = 10)]
public int StopLoss { get; set; }
[Parameter("Take Profit (pips)", DefaultValue = 10)]
public int TakeProfit { get; set; }
protected override void OnBar()
{
if(Trade.IsExecuting){
return;
}
if(MarketSeries.Close[MarketSeries.Close.Count-1] > MarketSeries.Close[MarketSeries.High.Count-2]){
upClose = 1;
}else{
upClose = 0;
}
if(MarketSeries.Close[MarketSeries.Close.Count-3] > MarketSeries.Close[MarketSeries.Close.Count-4]){
upCloseBefore = 1;
}else{
upCloseBefore = 0;
}
if((MarketSeries.High[MarketSeries.Close.Count-2] < MarketSeries.High[MarketSeries.Close.Count-3])
&&(MarketSeries.Low[MarketSeries.Close.Count-2]> MarketSeries.Low[MarketSeries.Close.Count-3])){
insideBar = 1;
}else{
insideBar = 0;
}
if(MarketSeries.Close[MarketSeries.Close.Count-1] < MarketSeries.Close[MarketSeries.Low.Count-2]){
downClose = 1;
}else{
downClose = 0;
}
if(MarketSeries.Close[MarketSeries.Close.Count-3] < MarketSeries.Close[MarketSeries.Close.Count-4]){
downCloseBefore = 1;
}else{
downCloseBefore = 0;
}
if(counter == 0){
if(upClose == 1 && insideBar == 1 && upCloseBefore == 1){
Trade.CreateMarketOrder(TradeType.Buy,Symbol,Volume);
}
if( downClose == 1 && insideBar == 1 && downCloseBefore == 1){
Trade.CreateMarketOrder(TradeType.Sell,Symbol,Volume);
}
}
}
protected override void OnPositionOpened(Position openedPosition)
{
position = openedPosition;
counter = 1;
Trade.ModifyPosition(openedPosition, GetAbsoluteStopLoss(openedPosition, StopLoss), GetAbsoluteTakeProfit(openedPosition, TakeProfit));
}
protected override void OnPositionClosed(Position position)
{
counter=0;
}
private double GetAbsoluteStopLoss(Position position, int stopLossInPips)
{
return position.TradeType == TradeType.Buy
? position.EntryPrice - Symbol.PipSize * stopLossInPips
: position.EntryPrice + Symbol.PipSize * stopLossInPips;
}
private double GetAbsoluteTakeProfit(Position position, int takeProfitInPips)
{
return position.TradeType == TradeType.Buy
? position.EntryPrice + Symbol.PipSize * takeProfitInPips
: position.EntryPrice - Symbol.PipSize * takeProfitInPips;
}
}
}
Have not tried much since I do not know how to do it!

AudioClips playing at start of game with audio source awake off

so I am coming to the end of a project I am currently working on and am running into a major issue with the audio. For some reason, my three recently added audio clips are playing at the start of my game instead of only playing on collision. I do only have one audio source on my player with the play on awake not checked. Could anyone explain what I am doing wrong?
The added clips are public AudioClip splashSound; public AudioClip reloadSound;and public AudioClip pageSound;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
public class RubyController : MonoBehaviour
{
public float speed = 3.0f;
private float boostTimer;
private bool boosting;
public int maxHealth = 5;
public GameObject projectilePrefab;
public int Score;
int Cog;
public int Book;
public TextMeshProUGUI scoreText;
public TextMeshProUGUI CogText;
public TextMeshProUGUI BookText;
public GameObject winTextObject;
public GameObject loseTextObject;
public GameObject LevelOneTextObject;
public GameObject BackgroundMusicObject;
public GameObject WinSoundObject;
public GameObject LoseSoundObject;
private static int Level = 1;
public AudioClip throwSound;
public AudioClip hitSound;
public AudioClip collectedClip;
public AudioClip splashSound;
public AudioClip reloadSound;
public AudioClip pageSound;
public int health { get { return currentHealth; }}
int currentHealth;
public float timeInvincible = 2.0f;
bool isInvincible;
float invincibleTimer;
Rigidbody2D rigidbody2d;
float horizontal;
float vertical;
public ParticleSystem HealthIncrease;
public ParticleSystem HealthDecrease;
Animator animator;
Vector2 lookDirection = new Vector2(1,0);
AudioSource audioSource;
public bool gameOver = false;
public static bool staticVar = false;
// Start is called before the first frame update
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
currentHealth = maxHealth;
audioSource = GetComponent<AudioSource>();
Score = 0;
Cog = 4;
Book = 0;
SetCogText();
SetBookText();
winTextObject.SetActive(false);
loseTextObject.SetActive(false);
LevelOneTextObject.SetActive(false);
WinSoundObject.SetActive(false);
LoseSoundObject.SetActive(false);
HealthIncrease.Stop();
HealthDecrease.Stop();
speed = 3;
boostTimer = 0;
boosting = false;
}
public void ChangeScore(int scoreAmount)
{
{
Score++;
scoreText.text = "Fixed Robots: " + Score.ToString();
}
if (Level == 1)
{
if (Score == 4)
{
LevelOneTextObject.SetActive(true);
}
}
if (Level == 2)
{
if(Score == 4 && Book == 4)
{
winTextObject.SetActive(true);
speed = 0;
WinSoundObject.SetActive(true);
BackgroundMusicObject.SetActive(false);
gameOver = true;
}
}
}
// Update is called once per frame
void Update()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
Vector2 move = new Vector2(horizontal, vertical);
if(!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
{
lookDirection.Set(move.x, move.y);
lookDirection.Normalize();
}
animator.SetFloat("Look X", lookDirection.x);
animator.SetFloat("Look Y", lookDirection.y);
animator.SetFloat("Speed", move.magnitude);
if (isInvincible)
{
invincibleTimer -= Time.deltaTime;
if (invincibleTimer < 0)
isInvincible = false;
}
if(Input.GetKeyDown(KeyCode.C) && Cog >= 1)
{
Cog = Cog -1;
SetCogText();
Launch();
}
else if (Input.GetKeyDown(KeyCode.C) && Cog ==0)
{
return;
}
if (Input.GetKeyDown(KeyCode.X))
{
RaycastHit2D hit = Physics2D.Raycast(rigidbody2d.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("NPC"));
if (hit.collider != null)
{
if (Score >= 4)
{
Level = 2;
SceneManager.LoadScene(1);
Score = 4;
}
else if (Score < 4)
{
NonPlayerCharacter character = hit.collider.GetComponent<NonPlayerCharacter>();
if (character != null)
{
character.DisplayDialog();
}
}
if (Book < 4)
{
NonPlayerCharacter character = hit.collider.GetComponent<NonPlayerCharacter>();
if (character != null)
{
character.DisplayDialog();
}
}
}
}
if(boosting)
{
boostTimer += Time.deltaTime;
if(boostTimer >= 5)
{
speed = 3;
boostTimer = 0;
boosting = false;
}
}
if (currentHealth == 0)
{
loseTextObject.SetActive(true);
{
speed = 0;
LoseSoundObject.SetActive(true);
BackgroundMusicObject.SetActive(false);
gameOver = true;
}
}
if(Input.GetKeyDown(KeyCode.R))
{
if (gameOver == true)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
void SetCogText()
{
if (Cog > 0)
{
CogText.text = "Cogs: " + Cog.ToString();
}
else if (Cog <= 0)
{
CogText.text = "Out of Cogs!";
}
}
void SetBookText()
{
if (Book > 0)
{
BookText.text = "Books: " + Book.ToString();
}
}
void FixedUpdate()
{
Vector2 position = rigidbody2d.position;
position.x = position.x + speed * horizontal * Time.deltaTime;
position.y = position.y + speed * vertical * Time.deltaTime;
rigidbody2d.MovePosition(position);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Cog"))
{
Cog = Cog + 3;
PlaySound(reloadSound);
other.gameObject.SetActive(false);
SetCogText();
}
if(other.tag == "SpeedBoost")
{
boosting = true;
speed = 6;
PlaySound(splashSound);
other.gameObject.SetActive(false);
}
if(other.tag == "Book")
{
Book = Book + 1;
PlaySound(pageSound);
other.gameObject.SetActive(false);
SetBookText();
}
}
public void ChangeHealth(int amount)
{
if (amount < 0)
{
if (isInvincible)
return;
isInvincible = true;
invincibleTimer = timeInvincible;
GameObject projectileObject = Instantiate(HealthDecrease.gameObject, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);
Projectile projectile = projectileObject.GetComponent<Projectile>();
PlaySound(hitSound);
}
if (amount < 5)
{
GameObject projectileObject = Instantiate(HealthIncrease.gameObject, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);
}
currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
UIHealthBar.instance.SetValue(currentHealth / (float)maxHealth);
}
void Launch()
{
GameObject projectileObject = Instantiate(projectilePrefab, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);
Projectile projectile = projectileObject.GetComponent<Projectile>();
projectile.Launch(lookDirection, 300);
animator.SetTrigger("Launch");
PlaySound(throwSound);
}
public void PlaySound(AudioClip clip)
{
audioSource.PlayOneShot(clip);
}
}

JsonConvert.DeserializeObject loading data types but not data values

My program gives the user the option to serialize a certain list List<Position>ListPosition that stores the data from the class Position. It does serialize pretty well and it sorta looks like the following
{
"PosZ": 0,
"PosX": 749,
"PosY": 208,
"Agent": {
"IsEdgeTree": false,
"ThisTreesCreator": null,
"Type": 0,
"Colour": "Green",
"Dimension": 25
}
},
{
"PosZ": 0,
"PosX": 724,
"PosY": 183,
"Agent": {
"IsEdgeTree": false,
"ThisTreesCreator": {
"IsEdgeTree": false,
"Position": {
"PosZ": 0,
"PosX": 749,
"PosY": 208
},
"ThisTreesCreator": null,
"Type": 0,
"Colour": "Green",
"Dimension": 25
},
"Type": 0,
"Colour": "Green",
"Dimension": 25
}
},
These are just a few examples.
The bit that is giving me problems is when I deserialize it.
When I inspect the bit of code that converts it JsonConvert.DeserializeObject<List<Position>>(JsonString);, everything reads fine but, when I equal it to the List I am trying to dump the data to AKA the same list the serialized data comes from but empty, the data doesn't load and I'm left with the correct structure but no values.
Values not showing up
To Deserialize, I call the following method from another Windows Forms:
public static void Deserialize()
{
if (Directory.Exists("Serialized"))
{
var FileName = "Serialized/PositionsSerialized_4.json";
var JsonString = File.ReadAllText(FileName);
ListPositions = JsonConvert.DeserializeObject<List<Position>>(JsonString);
}
else
MessageBox.Show("There's no directory");
}
I would really appreciate some help. If more information is needed, be sure to request it in the comments.
Thank you for your time.
public class Position
{
public static int MaxX { get; private set; }
public static int MaxY { get; private set; }
public static List<Position> ListPositions { get; private set; }
public static List<Position> ListTreePositions {
get
{
return ListPositions.Where(w => w.Agent?.Type == AgentType.Tree).ToList();
}
}
public static List<Position> ListDronePositions
{
get
{
return ListPositions.Where(w => w.Agent?.Type == AgentType.Drone).ToList();
}
}
public int PosX { get; private set; }
public int PosY { get; private set; }
public int PosZ;
private static object services;
public Agent Agent { get; private set; }
public Position()
{
ListPositions = new List<Position>();
}
public static void SetMaxValues(int maxX, int maxY)
{
MaxX = maxX;
MaxY = maxY;
}
public void FillNeighbours(int posX, int posY, int dim)
{
for (int i = 0; i < dim; i++)
{
for (int y = 0; y < dim; y++)
{
new Position(posX - (dim - y), posY - (dim - i), Agent);
}
}
}
public static Position CreateNewRandomPosition()
{
Random rnd = new Random();
int rndX;
int rndY;
Position position = null;
while (position == null)
{
rndX = rnd.Next(MaxX - 100);
rndY = rnd.Next(MaxY - 100);
position = CreatePosition(rndX, rndY);
}
return position;
}
public static Bitmap ExportBitmap()
{
return ExportBitmap(0, 0, MaxX, MaxY, ListPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY)
{
var listPositions = ListPositions.Where(w => (w.Agent != null) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, AgentType agentType)
{
var listPositions = ListPositions.Where(w => (w.Agent.Type == agentType) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, AgentType[] agentType)
{
var listPositions = ListPositions.Where(w => (agentType.Contains(w.Agent.Type)) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
private static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, List<Position> positions)
{
Bitmap bmp = new Bitmap(maxX - posX, maxY - posY);
if (Agent.Sprites.Count() == 0)
{
Agent.LoadSprites();
}
Graphics g = Graphics.FromImage(bmp);
foreach (var item in positions)
{
var SpriteWidth = Agent.Sprites[item.Agent.Type].Width / 2;
var SpriteHeight = Agent.Sprites[item.Agent.Type].Height / 2;
g.DrawImage(Agent.Sprites[item.Agent.Type], new Point(item.PosX - SpriteWidth - posX, item.PosY - SpriteHeight - posY));
}
if (!Directory.Exists("Photos"))
{
Directory.CreateDirectory("Photos");
}
int count = Directory.GetFiles("Photos", "*").Length;
bmp.Save("Photos\\Img" + count + 1 + ".png", System.Drawing.Imaging.ImageFormat.Png);
return bmp;
}
public Position(int poxX, int poxY)
{
PosX = poxX;
PosY = poxY;
if (Agent != null)
ListPositions.Add(this);
}
public Position(int posX, int posY, Agent agent)
{
PosX = posX;
PosY = posY;
Agent = agent;
if (Agent != null)
ListPositions.Add(this);
}
public void AssociateAgent(Agent agent)
{
Agent = agent;
if (Agent != null)
ListPositions.Add(this);
}
public static bool CheckPositionIsValid(int poxX, int poxY)
{
int? NullableMaxX = MaxX;
int? NullableMaxY = MaxY;
var posXValid = poxX > 0 && (poxX <= MaxX || NullableMaxX == null); //verifies if posX is within the boundries of the premises
var posYValid = poxY > 0 && (poxY <= MaxY || NullableMaxY == null); //verifies if posY is within the boundries of the premises
return posXValid && posYValid; //returns if they are both valid
}
public static Position Find(int poxX, int poxY)
{
return ListPositions.Find(f => f.PosX == poxX && f.PosY == poxY) ?? null;
}
public static Position CreatePosition(int poxX, int poxY)
{
if (Find(poxX, poxY) == null)
if (CheckPositionIsValid(poxX, poxY))
return new Position(poxX, poxY);
else
return null;
else
return null;
}
public Dictionary<int, Position> ListNeighbourPositions(int dim = 1)
{
Dictionary<int, Position> NeighbourList = new Dictionary<int, Position>();
for (int i = 1; i < 9; i++)
{
if (i != 5)
{
var position = FindNeighbour(i, dim);
if (position != null)
NeighbourList.Add(i, position);
}
}
return NeighbourList;
}
public Position FindNeighbour(int neighbourPos, int dim)
{
var position = FindNeighbourbyPosition(neighbourPos, dim);
return Find(position.Item1, position.Item2);
}
public Tuple<int, int> FindNeighbourbyPosition(int neighbourPos, int dim = 1)
{
int neighbourPosX;
int neighbourPosY;
switch (neighbourPos)
{
case 1:
neighbourPosX = PosX - dim;
neighbourPosY = PosY - dim;
break;
case 2:
neighbourPosX = PosX;
neighbourPosY = PosY - dim;
break;
case 3:
neighbourPosX = PosX + dim;
neighbourPosY = PosY - dim;
break;
case 4:
neighbourPosX = PosX - dim;
neighbourPosY = PosY;
break;
case 6:
neighbourPosX = PosX + dim;
neighbourPosY = PosY;
break;
case 7:
neighbourPosX = PosX - dim;
neighbourPosY = PosY + dim;
break;
case 8:
neighbourPosX = PosX;
neighbourPosY = PosY + dim;
break;
case 9:
neighbourPosX = PosX + dim;
neighbourPosY = PosY + dim;
break;
default:
return null;
}
return new Tuple<int, int>(neighbourPosX, neighbourPosY);
}
public void UpdatePosition(int newX, int newY)
{
PosX = newX;
PosY = newY;
}
public static void Serialize()
{
if (!Directory.Exists("Serialized"))
{
Directory.CreateDirectory("Serialized");
}
int count = Directory.GetFiles("Serialized", "*").Length;
string fileName = "Serialized/PositionsSerialized_" + count + ".json";
string jsonString = JsonConvert.SerializeObject(ListPositions, Formatting.Indented, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
File.WriteAllText(fileName, jsonString);
}
public static void Deserialize()
{
if (Directory.Exists("Serialized"))
{
var FileName = "Serialized/PositionsSerialized_4.json";
var JsonString = File.ReadAllText(FileName);
ListPositions = JsonConvert.DeserializeObject<List<Position>>(JsonString);
}
else
MessageBox.Show("There's no directory");
}
}
The reason of your problem is because you defined setters as private...
public static int MaxX { get; private set; }
public static int MaxY { get; private set; }
public int PosX { get; private set; }
public int PosY { get; private set; }
it should be...
public static int MaxX { get; set; }
public static int MaxY { get; set; }
public int PosX { get; set; }
public int PosY { get; set; }

Playing specific sounds when an object is revealed

I have completed a tutorial on how to make a memory card, everything works great, I can play the game and match all the cards (20 or 30 or 40 for different categories cause I have 6 of them) and I added a timer. I can even reset the game and start all over, and all the cards are randomly sorted out.
But I want to go beyond the tutorial and put some sound effects in the game to make it more fun. I get that you can play sounds on mouse clicks and stuff, but I want to play sounds when specific cards are revealed. Duck card appears and you hear a quacking sound or his name. I'm a beginner and I don't know how to add it.
I'm not sure if I would start a new C# script or add to my existing (PictureManager) script or (Picture) script.
Any help would be appreciated. Thank you. These are my (PictureManager) and (Picture) script for the game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PictureManager : MonoBehaviour
{
public Picture PicturePrefab;
public Transform PicSpawnPosition;
public Vector2 StartPosition = new Vector2(-2.15f, 3.62f);
public AudioSource WinSound;
public AudioSource BgSound;
[Space]
[Header("End Game Screen")]
public GameObject EndGamePanel;
public GameObject NewBestScoreText;
public GameObject YourScoreText;
public GameObject EndTimeText;
/*to rremove
public List<AudioClip> Vegetabels = new List<AudioClip>();
private AudioSource audioSource;
to remove*/
public enum GameState
{
NoAction,
MovingOnPositions,
DeletingPuzzles,
FlipBack,
Checking,
GameEnd
};
public enum PuzzleState
{
PuzzleRotating,
CanRotate,
};
public enum RevealedState
{
NoRevealed,
OneRevealed,
TwoRevealed
};
[HideInInspector]
public GameState CurrentGameState;
[HideInInspector]
public PuzzleState CurrentPuzzleState;
[HideInInspector]
public RevealedState PuzzleRevealedNumber;
[HideInInspector]
public List<Picture> PictureList;
private Vector2 _offset = new Vector2(1.42f, 1.52f);
private Vector2 _offsetFor15Pairs = new Vector2(1.08f, 1.22f);
private Vector2 _offsetFor20Pairs = new Vector2(1.08f, 1.0f);
private Vector3 _newScaleDown = new Vector3(0.9f, 0.9f, 0.001f);
private List<Material> _materialList = new List<Material>();
private List<string> _texturePathList = new List<string>();
private Material _firstMaterial;
private string _firstTexturePath;
private int _firstRevealedPic;
private int _secondRevealedPic;
private int _revealedPicNumber = 0;
private int _picToDestroy1;
private int _picToDestroy2;
private bool _corutineStarted = false;
private int _pairNumbers;
private int _removedPairs;
private Timer _gameTimer;
void Start()
{
//BgSound.Play();
CurrentGameState = GameState.NoAction;
CurrentPuzzleState = PuzzleState.CanRotate;
PuzzleRevealedNumber = RevealedState.NoRevealed;
_revealedPicNumber = 0;
_firstRevealedPic = -1;
_secondRevealedPic = -1;
_removedPairs = 0;
_pairNumbers = (int)GameSettings.Instance.GetPairNumber();
_gameTimer = GameObject.Find("Main Camera").GetComponent<Timer>();
LoadMaterials();
if(GameSettings.Instance.GetPairNumber()== GameSettings.EPairNumber.E10Pairs)
{
CurrentGameState = GameState.MovingOnPositions;
SpwanPictureMesh(4, 5, StartPosition, _offset, false);
MovePicture(4, 5, StartPosition, _offset);
}
else if (GameSettings.Instance.GetPairNumber() == GameSettings.EPairNumber.E15Pairs)
{
CurrentGameState = GameState.MovingOnPositions;
SpwanPictureMesh(5, 6, StartPosition, _offset, false);
MovePicture(5, 6, StartPosition, _offsetFor15Pairs);
}
else if (GameSettings.Instance.GetPairNumber() == GameSettings.EPairNumber.E20Pairs)
{
CurrentGameState = GameState.MovingOnPositions;
SpwanPictureMesh(5, 8, StartPosition, _offset, true);
MovePicture(5, 8, StartPosition, _offsetFor20Pairs);
}
}
public void CheckPicture()
{
CurrentGameState = GameState.Checking;
_revealedPicNumber = 0;
for(int id = 0; id < PictureList.Count; id++)
{
if(PictureList[id].Revealed && _revealedPicNumber < 2)
{
if(_revealedPicNumber == 0)
{
_firstRevealedPic = id;
_revealedPicNumber++;
//audioSource.PlayOneShot(Vegetabels[id]);
}
else if (_revealedPicNumber == 1)
{
_secondRevealedPic = id;
_revealedPicNumber++;
}
}
if (_revealedPicNumber == 2)
{
if (PictureList[_firstRevealedPic].GetIndex() == PictureList[_secondRevealedPic].GetIndex() && _firstRevealedPic != _secondRevealedPic)
{
CurrentGameState = GameState.DeletingPuzzles;
_picToDestroy1 = _firstRevealedPic;
_picToDestroy2 = _secondRevealedPic;
}
else
{
CurrentGameState = GameState.FlipBack;
}
}
}
CurrentPuzzleState = PictureManager.PuzzleState.CanRotate;
if(CurrentGameState == GameState.Checking)
{
CurrentGameState = GameState.NoAction;
}
}
private void DestroyPicture()
{
PuzzleRevealedNumber = RevealedState.NoRevealed;
PictureList[_picToDestroy1].Deactivate();
PictureList[_picToDestroy2].Deactivate();
_revealedPicNumber = 0;
_removedPairs++;
CurrentGameState = GameState.NoAction;
CurrentPuzzleState = PuzzleState.CanRotate;
}
private IEnumerator FlipBack()
{
_corutineStarted = true;
yield return new WaitForSeconds(0.5f);
PictureList[_firstRevealedPic].FlipBack();
PictureList[_secondRevealedPic].FlipBack();
PictureList[_firstRevealedPic].Revealed = false;
PictureList[_secondRevealedPic].Revealed = false;
PuzzleRevealedNumber = RevealedState.NoRevealed;
CurrentGameState = GameState.NoAction;
_corutineStarted = false;
}
private void LoadMaterials()
{
var materialFilePath = GameSettings.Instance.GetMaterialDirectoryName();
var textureFilePath = GameSettings.Instance.GetPuzzleCategoryTextureDirectoryName();
var pairNumber = (int)GameSettings.Instance.GetPairNumber();
const string matBaseName = "Pic";
var firstMaterialName = "Back";
for(var index = 1; index <= pairNumber; index++)
{
var currentFilePath = materialFilePath + matBaseName + index;
Material mat = Resources.Load(currentFilePath, typeof(Material)) as Material;
_materialList.Add(mat);
var currentTextureFilePath = textureFilePath + matBaseName + index;
_texturePathList.Add(currentTextureFilePath);
}
_firstTexturePath = textureFilePath + firstMaterialName;
_firstMaterial = Resources.Load(materialFilePath + firstMaterialName, typeof(Material)) as Material;
}
void Update()
{
if (PauseMenu.isPaused == false) {
if (CurrentGameState == GameState.DeletingPuzzles)
{
if(CurrentPuzzleState == PuzzleState.CanRotate)
{
DestroyPicture();
CheckGameEnd();
}
}
if (CurrentGameState == GameState.FlipBack)
{
if(CurrentPuzzleState == PuzzleState.CanRotate && _corutineStarted == false)
{
StartCoroutine(FlipBack());
}
}
if(CurrentGameState == GameState.GameEnd)
{
if(PictureList[_firstRevealedPic].gameObject.activeSelf == false &&
PictureList[_secondRevealedPic].gameObject.activeSelf == false &&
EndGamePanel.activeSelf == false)
{
ShowEndGameInformation();
if (GameSettings.Instance.IsSoundEffectMutedPermanently() == false)
WinSound.Play();
//BgSound.Pause();
}
}
}
}
private bool CheckGameEnd()
{
if(_removedPairs == _pairNumbers && CurrentGameState != GameState.GameEnd)
{
CurrentGameState = GameState.GameEnd;
_gameTimer.StopTimer();
Config.PlaceScoreOnBorad(_gameTimer.GetCurrentTime());
}
return (CurrentGameState == GameState.GameEnd);
}
private void ShowEndGameInformation()
{
EndGamePanel.SetActive(true);
if(Config.IsBestScore())
{
NewBestScoreText.SetActive(true);
YourScoreText.SetActive(false);
}
else
{
NewBestScoreText.SetActive(false);
YourScoreText.SetActive(true);
}
var timer = _gameTimer.GetCurrentTime();
var minutes = Mathf.Floor(timer / 60);
var seconds = Mathf.RoundToInt(timer % 60);
var newText = minutes.ToString("00") + ":" + seconds.ToString("00");
EndTimeText.GetComponent<Text>().text = newText;
}
private void SpwanPictureMesh(int rows, int columns, Vector2 Pos, Vector2 offset, bool scaleDown)
{
for(int col = 0; col < columns; col++)
{
for(int row = 0; row < rows; row++)
{
var tempPicture = (Picture)Instantiate(PicturePrefab, PicSpawnPosition.position, PicturePrefab.transform.rotation);
if(scaleDown)
{
tempPicture.transform.localScale = _newScaleDown;
}
tempPicture.name = tempPicture.name + 'c' + col + 'r' + row;
PictureList.Add(tempPicture);
}
}
ApplyTextures();
}
public void ApplyTextures()
{
var rndMatIndex = Random.Range(0, _materialList.Count);
var AppliedTimes = new int[_materialList.Count];
for(int i = 0; i< _materialList.Count; i++)
{
AppliedTimes[i] = 0;
}
foreach(var o in PictureList)
{
var randPrevious = rndMatIndex;
var counter = 0;
var forceMat = false;
while(AppliedTimes[rndMatIndex] >= 2 || ((randPrevious == rndMatIndex) && !forceMat))
{
rndMatIndex = Random.Range(0, _materialList.Count);
counter++;
if(counter > 100)
{
for (var j = 0; j < _materialList.Count; j++)
{
if(AppliedTimes[j] < 2)
{
rndMatIndex = j;
forceMat = true;
}
}
if (forceMat == false)
return;
}
}
o.SetFirstMaterial(_firstMaterial, _firstTexturePath);
o.ApplyFirstMaterial();
o.SetSecondMaterial(_materialList[rndMatIndex], _texturePathList[rndMatIndex]);
o.SetIndex(rndMatIndex);
o.Revealed = false;
AppliedTimes[rndMatIndex] += 1;
forceMat = false;
}
}
private void MovePicture(int rows, int columns, Vector2 pos, Vector2 offset)
{
var index = 0;
for(var col = 0; col < columns; col++)
{
for(int row = 0; row < rows; row++)
{
var targetPosition = new Vector3((pos.x + (offset.x * row)), (pos.y - (offset.y * col)), 0.0f);
StartCoroutine(MoveToPosition(targetPosition, PictureList[index]));
index++;
}
}
}
private IEnumerator MoveToPosition(Vector3 target, Picture obj)
{
var randomDis = 7;
while(obj.transform.position !=target)
{
obj.transform.position = Vector3.MoveTowards(obj.transform.position, target, randomDis * Time.deltaTime);
yield return 0;
}
}
}
----------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Picture : MonoBehaviour
{
public AudioClip PressSound;
private Material _firstMaterial;
private Material _secondMaterial;
private Quaternion _currentRotation;
[HideInInspector] public bool Revealed = false;
private PictureManager _pictureManager;
private bool _clicked = false;
private int _index;
private AudioSource _audio;
public void SetIndex(int id)
{
_index = id;
}
public int GetIndex()
{
return _index;
}
void Start()
{
Revealed = false;
_clicked = false;
_pictureManager = GameObject.Find("[PictureManager]").GetComponent<PictureManager>();
_currentRotation = gameObject.transform.rotation;
_audio = GetComponent<AudioSource>();
_audio.clip = PressSound;
}
void Update()
{
}
private void OnMouseDown()
{
if(_clicked == false)
{
if (PauseMenu.isPaused == false)
{
_pictureManager.CurrentPuzzleState = PictureManager.PuzzleState.PuzzleRotating;
if (GameSettings.Instance.IsSoundEffectMutedPermanently() == false)
_audio.Play();
StartCoroutine(LoopRotation(45, false));
_clicked = true;
}
}
}
public void FlipBack()
{
if (gameObject.activeSelf)
{
_pictureManager.CurrentPuzzleState = PictureManager.PuzzleState.PuzzleRotating;
Revealed = false;
/*if (GameSettings.Instance.IsSoundEffectMutedPermanently() == false)
_audio.Play();*/
StartCoroutine(LoopRotation(45, true));
}
}
IEnumerator LoopRotation(float angle, bool FirstMat)
{
var rot = 0f;
const float dir = 1f;
const float rotSpeed = 180.0f;
const float rotSpeed1 = 90.0f;
var startAngle = angle;
var assigned = false;
if(FirstMat)
{
while(rot < angle)
{
var step = Time.deltaTime * rotSpeed1;
gameObject.GetComponent<Transform>().Rotate(new Vector3(0, 2, 0) * step * dir);
if(rot >= (startAngle - 2) && assigned == false)
{
ApplyFirstMaterial();
assigned = true;
}
rot += (1 * step * dir);
yield return null;
}
}
else
{
while (angle > 0)
{
float step = Time.deltaTime * rotSpeed;
gameObject.GetComponent<Transform>().Rotate(new Vector3(0, 2, 0) * step * dir);
angle -= (1 * step * dir);
yield return null;
}
}
gameObject.GetComponent<Transform>().rotation = _currentRotation;
if (!FirstMat)
{
Revealed = true;
ApplySecondMaterial();
_pictureManager.CheckPicture();
}
else
{
_pictureManager.PuzzleRevealedNumber = PictureManager.RevealedState.NoRevealed;
_pictureManager.CurrentPuzzleState = PictureManager.PuzzleState.CanRotate;
}
_clicked = false;
}
public void SetFirstMaterial(Material mat, string texturePath)
{
_firstMaterial = mat;
_firstMaterial.mainTexture = Resources.Load(texturePath, typeof(Texture2D)) as Texture2D;
}
public void SetSecondMaterial(Material mat, string texturePath)
{
_secondMaterial = mat;
_secondMaterial.mainTexture = Resources.Load(texturePath, typeof(Texture2D)) as Texture2D;
}
public void ApplyFirstMaterial()
{
gameObject.GetComponent<Renderer>().material = _firstMaterial;
}
public void ApplySecondMaterial()
{
gameObject.GetComponent<Renderer>().material = _secondMaterial;
}
public void Deactivate()
{
StartCoroutine(DeactivateCorutine());
}
private IEnumerator DeactivateCorutine()
{
Revealed = false;
yield return new WaitForSeconds(1f);
gameObject.SetActive(false);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PictureManager : MonoBehaviour
{
public Picture PicturePrefab;
public Transform PicSpawnPosition;
public Vector2 StartPosition = new Vector2(-2.15f, 3.62f);
public AudioSource WinSound;
public AudioSource BgSound;
[Space]
[Header("End Game Screen")]
public GameObject EndGamePanel;
public GameObject NewBestScoreText;
public GameObject YourScoreText;
public GameObject EndTimeText;
/*to rremove
public List<AudioClip> Vegetabels = new List<AudioClip>();
private AudioSource audioSource;
to remove*/
public enum GameState
{
NoAction,
MovingOnPositions,
DeletingPuzzles,
FlipBack,
Checking,
GameEnd
};
public enum PuzzleState
{
PuzzleRotating,
CanRotate,
};
public enum RevealedState
{
NoRevealed,
OneRevealed,
TwoRevealed
};
[HideInInspector]
public GameState CurrentGameState;
[HideInInspector]
public PuzzleState CurrentPuzzleState;
[HideInInspector]
public RevealedState PuzzleRevealedNumber;
[HideInInspector]
public List<Picture> PictureList;
private Vector2 _offset = new Vector2(1.42f, 1.52f);
private Vector2 _offsetFor15Pairs = new Vector2(1.08f, 1.22f);
private Vector2 _offsetFor20Pairs = new Vector2(1.08f, 1.0f);
private Vector3 _newScaleDown = new Vector3(0.9f, 0.9f, 0.001f);
private List<Material> _materialList = new List<Material>();
private List<string> _texturePathList = new List<string>();
private Material _firstMaterial;
private string _firstTexturePath;
private int _firstRevealedPic;
private int _secondRevealedPic;
private int _revealedPicNumber = 0;
private int _picToDestroy1;
private int _picToDestroy2;
private bool _corutineStarted = false;
private int _pairNumbers;
private int _removedPairs;
private Timer _gameTimer;
void Start()
{
//BgSound.Play();
CurrentGameState = GameState.NoAction;
CurrentPuzzleState = PuzzleState.CanRotate;
PuzzleRevealedNumber = RevealedState.NoRevealed;
_revealedPicNumber = 0;
_firstRevealedPic = -1;
_secondRevealedPic = -1;
_removedPairs = 0;
_pairNumbers = (int)GameSettings.Instance.GetPairNumber();
_gameTimer = GameObject.Find("Main Camera").GetComponent<Timer>();
LoadMaterials();
if(GameSettings.Instance.GetPairNumber()== GameSettings.EPairNumber.E10Pairs)
{
CurrentGameState = GameState.MovingOnPositions;
SpwanPictureMesh(4, 5, StartPosition, _offset, false);
MovePicture(4, 5, StartPosition, _offset);
}
else if (GameSettings.Instance.GetPairNumber() == GameSettings.EPairNumber.E15Pairs)
{
CurrentGameState = GameState.MovingOnPositions;
SpwanPictureMesh(5, 6, StartPosition, _offset, false);
MovePicture(5, 6, StartPosition, _offsetFor15Pairs);
}
else if (GameSettings.Instance.GetPairNumber() == GameSettings.EPairNumber.E20Pairs)
{
CurrentGameState = GameState.MovingOnPositions;
SpwanPictureMesh(5, 8, StartPosition, _offset, true);
MovePicture(5, 8, StartPosition, _offsetFor20Pairs);
}
}
public void CheckPicture()
{
CurrentGameState = GameState.Checking;
_revealedPicNumber = 0;
for(int id = 0; id < PictureList.Count; id++)
{
if(PictureList[id].Revealed && _revealedPicNumber < 2)
{
if(_revealedPicNumber == 0)
{
_firstRevealedPic = id;
_revealedPicNumber++;
//audioSource.PlayOneShot(Vegetabels[id]);
}
else if (_revealedPicNumber == 1)
{
_secondRevealedPic = id;
_revealedPicNumber++;
}
}
if (_revealedPicNumber == 2)
{
if (PictureList[_firstRevealedPic].GetIndex() == PictureList[_secondRevealedPic].GetIndex() && _firstRevealedPic != _secondRevealedPic)
{
CurrentGameState = GameState.DeletingPuzzles;
_picToDestroy1 = _firstRevealedPic;
_picToDestroy2 = _secondRevealedPic;
}
else
{
CurrentGameState = GameState.FlipBack;
}
}
}
CurrentPuzzleState = PictureManager.PuzzleState.CanRotate;
if(CurrentGameState == GameState.Checking)
{
CurrentGameState = GameState.NoAction;
}
}
private void DestroyPicture()
{
PuzzleRevealedNumber = RevealedState.NoRevealed;
PictureList[_picToDestroy1].Deactivate();
PictureList[_picToDestroy2].Deactivate();
_revealedPicNumber = 0;
_removedPairs++;
CurrentGameState = GameState.NoAction;
CurrentPuzzleState = PuzzleState.CanRotate;
}
private IEnumerator FlipBack()
{
_corutineStarted = true;
yield return new WaitForSeconds(0.5f);
PictureList[_firstRevealedPic].FlipBack();
PictureList[_secondRevealedPic].FlipBack();
PictureList[_firstRevealedPic].Revealed = false;
PictureList[_secondRevealedPic].Revealed = false;
PuzzleRevealedNumber = RevealedState.NoRevealed;
CurrentGameState = GameState.NoAction;
_corutineStarted = false;
}
private void LoadMaterials()
{
var materialFilePath = GameSettings.Instance.GetMaterialDirectoryName();
var textureFilePath = GameSettings.Instance.GetPuzzleCategoryTextureDirectoryName();
var pairNumber = (int)GameSettings.Instance.GetPairNumber();
const string matBaseName = "Pic";
var firstMaterialName = "Back";
for(var index = 1; index <= pairNumber; index++)
{
var currentFilePath = materialFilePath + matBaseName + index;
Material mat = Resources.Load(currentFilePath, typeof(Material)) as Material;
_materialList.Add(mat);
var currentTextureFilePath = textureFilePath + matBaseName + index;
_texturePathList.Add(currentTextureFilePath);
}
_firstTexturePath = textureFilePath + firstMaterialName;
_firstMaterial = Resources.Load(materialFilePath + firstMaterialName, typeof(Material)) as Material;
}
void Update()
{
if (PauseMenu.isPaused == false) {
if (CurrentGameState == GameState.DeletingPuzzles)
{
if(CurrentPuzzleState == PuzzleState.CanRotate)
{
DestroyPicture();
CheckGameEnd();
}
}
if (CurrentGameState == GameState.FlipBack)
{
if(CurrentPuzzleState == PuzzleState.CanRotate && _corutineStarted == false)
{
StartCoroutine(FlipBack());
}
}
if(CurrentGameState == GameState.GameEnd)
{
if(PictureList[_firstRevealedPic].gameObject.activeSelf == false &&
PictureList[_secondRevealedPic].gameObject.activeSelf == false &&
EndGamePanel.activeSelf == false)
{
ShowEndGameInformation();
if (GameSettings.Instance.IsSoundEffectMutedPermanently() == false)
WinSound.Play();
//BgSound.Pause();
}
}
}
}
private bool CheckGameEnd()
{
if(_removedPairs == _pairNumbers && CurrentGameState != GameState.GameEnd)
{
CurrentGameState = GameState.GameEnd;
_gameTimer.StopTimer();
Config.PlaceScoreOnBorad(_gameTimer.GetCurrentTime());
}
return (CurrentGameState == GameState.GameEnd);
}
private void ShowEndGameInformation()
{
EndGamePanel.SetActive(true);
if(Config.IsBestScore())
{
NewBestScoreText.SetActive(true);
YourScoreText.SetActive(false);
}
else
{
NewBestScoreText.SetActive(false);
YourScoreText.SetActive(true);
}
var timer = _gameTimer.GetCurrentTime();
var minutes = Mathf.Floor(timer / 60);
var seconds = Mathf.RoundToInt(timer % 60);
var newText = minutes.ToString("00") + ":" + seconds.ToString("00");
EndTimeText.GetComponent<Text>().text = newText;
}
private void SpwanPictureMesh(int rows, int columns, Vector2 Pos, Vector2 offset, bool scaleDown)
{
for(int col = 0; col < columns; col++)
{
for(int row = 0; row < rows; row++)
{
var tempPicture = (Picture)Instantiate(PicturePrefab, PicSpawnPosition.position, PicturePrefab.transform.rotation);
if(scaleDown)
{
tempPicture.transform.localScale = _newScaleDown;
}
tempPicture.name = tempPicture.name + 'c' + col + 'r' + row;
PictureList.Add(tempPicture);
}
}
ApplyTextures();
}
public void ApplyTextures()
{
var rndMatIndex = Random.Range(0, _materialList.Count);
var AppliedTimes = new int[_materialList.Count];
for(int i = 0; i< _materialList.Count; i++)
{
AppliedTimes[i] = 0;
}
foreach(var o in PictureList)
{
var randPrevious = rndMatIndex;
var counter = 0;
var forceMat = false;
while(AppliedTimes[rndMatIndex] >= 2 || ((randPrevious == rndMatIndex) && !forceMat))
{
rndMatIndex = Random.Range(0, _materialList.Count);
counter++;
if(counter > 100)
{
for (var j = 0; j < _materialList.Count; j++)
{
if(AppliedTimes[j] < 2)
{
rndMatIndex = j;
forceMat = true;
}
}
if (forceMat == false)
return;
}
}
o.SetFirstMaterial(_firstMaterial, _firstTexturePath);
o.ApplyFirstMaterial();
o.SetSecondMaterial(_materialList[rndMatIndex], _texturePathList[rndMatIndex]);
o.SetIndex(rndMatIndex);
o.Revealed = false;
AppliedTimes[rndMatIndex] += 1;
forceMat = false;
}
}
private void MovePicture(int rows, int columns, Vector2 pos, Vector2 offset)
{
var index = 0;
for(var col = 0; col < columns; col++)
{
for(int row = 0; row < rows; row++)
{
var targetPosition = new Vector3((pos.x + (offset.x * row)), (pos.y - (offset.y * col)), 0.0f);
StartCoroutine(MoveToPosition(targetPosition, PictureList[index]));
index++;
}
}
}
private IEnumerator MoveToPosition(Vector3 target, Picture obj)
{
var randomDis = 7;
while(obj.transform.position !=target)
{
obj.transform.position = Vector3.MoveTowards(obj.transform.position, target, randomDis * Time.deltaTime);
yield return 0;
}
}
}

Unity:Unable to spawn Enemy wave?

I am building a survival shooter, I am using a script that I got from an other project link,the script only spawns the 1st wave and then nothing happens.
It dosent give any warning nor any error
EnemyWave Script
public class WaveManager : MonoBehaviour {
PlayerHealth playerHealth;
public float bufferDistance = 200;
public float timeBetweenWaves = 5f;
public float spawnTime = 3f;
public int startingWave = 1;
public int startingDifficulty = 1;
public Text number;
[HideInInspector]
public int enemiesAlive = 0;
[System.Serializable]
public class Wave {
public Entry[] entries;
[System.Serializable]
public class Entry {
public GameObject enemy;
public int count;
[System.NonSerialized]
public int spawned;
}
}
// All our waves.
public Wave[] waves;
Vector3 spawnPosition = Vector3.zero;
int waveNumber;
float timer;
Wave currentWave;
int spawnedThisWave = 0;
int totalToSpawnForWave;
bool shouldSpawn = false;
int difficulty;
void Start() {
playerHealth = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
waveNumber = startingWave > 0 ? startingWave - 1 : 0;
difficulty = startingDifficulty;
StartCoroutine("StartNextWave");
}
void Update() {
if (!shouldSpawn) {
return;
}
if (spawnedThisWave == totalToSpawnForWave && enemiesAlive == 0) {
StartCoroutine("StartNextWave");
return;
}
timer += Time.deltaTime;
if (timer >= spawnTime) {
foreach (Wave.Entry entry in currentWave.entries) {
if (entry.spawned < (entry.count * difficulty)) {
Spawn(entry);
}
}
}
}
IEnumerator StartNextWave() {
shouldSpawn = false;
yield return new WaitForSeconds(timeBetweenWaves);
if (waveNumber == waves.Length) {
waveNumber = 0;
difficulty++;
}
currentWave = waves[waveNumber];
totalToSpawnForWave = 0;
foreach (Wave.Entry entry in currentWave.entries) {
totalToSpawnForWave += (entry.count * difficulty);
}
spawnedThisWave = 0;
shouldSpawn = true;
waveNumber++;
number.text = (waveNumber + ((difficulty - 1) * waves.Length)).ToString();
number.GetComponent<Animation>().Play();
}
void Spawn(Wave.Entry entry) {
timer = 0f;
if (playerHealth.currentHealth <= 0f) {
return;
}
Vector3 randomPosition = Random.insideUnitSphere * 10;
randomPosition.y = 0;
UnityEngine.AI.NavMeshHit hit;
if (!UnityEngine.AI.NavMesh.SamplePosition(randomPosition, out hit, 5, 1)) {
return;
}
spawnPosition = hit.position;
Vector3 screenPos = Camera.main.WorldToScreenPoint(spawnPosition);
if ((screenPos.x > -bufferDistance && screenPos.x < (Screen.width + bufferDistance)) &&
(screenPos.y > -bufferDistance && screenPos.y < (Screen.height + bufferDistance)))
{
return;
}
GameObject enemy = Instantiate(entry.enemy, spawnPosition, Quaternion.identity) as GameObject;
enemy.GetComponent<EnemyHealth>().startingHealth *= difficulty;
enemy.GetComponent<EnemyHealth>().scoreValue *= difficulty;
entry.spawned++;
spawnedThisWave++;
enemiesAlive++;
}}

Categories