How to limit the spawn object in unity - c#

I'm trying to add a limit in a spawn objects. I want to keep the spawn object to one. but it's not working at all.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Spawn : MonoBehaviour {
public Spawn04[] pest;
public GameObject plantPest;
void Start () {
}
[System.Obsolete]
void Update () {
if(plantPest.active)
{
SpawnObjects();
}
}
void SpawnObjects()
{
int i = Random.Range(0, 100);
for(int j = 0; j < pest.Length; j++)
{
if(i >= pest[j].minProbabilityRange && i <= pest[j].maxProbabilityRange)
{
Instantiate(pest[j].spawnObject, transform.position, transform.rotation);
break;
}
if(pest[j].pestCount >= pest[j].maxNumber)
{
Destroy(this.gameObject);
}
}
}
}
[System.Serializable]
public class Spawn04
{
public GameObject spawnObject;
public int minProbabilityRange = 0;
public int maxProbabilityRange = 0;
public int maxNumber = 1;
public int pestCount = 0;
}

All you need is a counter and a variable to controlling your max count. Just remember to decrement the counter after the object is despawned.
public class Spawn : MonoBehaviour {
public Spawn04[] pest;
public GameObject plantPest;
public int maxPests = 10; // ADDED
private int pestsSpawned = 0; // ADDED
[System.Obsolete]
void Update () {
if(plantPest.active)
{
SpawnObjects();
}
}
void SpawnObjects()
{
// NEW CHECK
if (pestsSpawned < maxPests) {
int i = Random.Range(0, 100);
for(int j = 0; j < pest.Length; j++)
{
if(i >= pest[j].minProbabilityRange && i <= pest[j].maxProbabilityRange)
{
Instantiate(pest[j].spawnObject, transform.position, transform.rotation);
pestsSpawned++; // COUNT TRACKER
break;
}
}
}
}
}
Another option is using a static variable on the Spawn04 object as such:
public class Spawn : MonoBehaviour {
public Spawn04[] pest;
public GameObject plantPest;
public int maxPests = 10; // ADDED
[System.Obsolete]
void Update () {
if(plantPest.active)
{
SpawnObjects();
}
}
void SpawnObjects()
{
// NEW CHECK
if (Spawn04.spawnCount <= maxPests) {
int i = Random.Range(0, 100);
for(int j = 0; j < pest.Length; j++)
{
if(i >= pest[j].minProbabilityRange && i <= pest[j].maxProbabilityRange)
{
Instantiate(pest[j].spawnObject, transform.position, transform.rotation);
Spawn04.spawnCount++; // COUNT TRACKER
break;
}
}
}
}
}
[System.Serializable]
public class Spawn04
{
public GameObject spawnObject;
public int minProbabilityRange = 0;
public int maxProbabilityRange = 0;
public static int spawnCount = 0; // ADDED
}
Hope this gives some inspiration on how to address this issue.

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!

Error in unity c#: error CS0721: 'Random': static types cannot be used as parameters

I found a code on the Internet that works like Python's random.choices():
static class RandomUtils
{
public static string Choice(this Random rnd, IEnumerable<string> choices, IEnumerable<int> weights)
{
var cumulativeWeight = new List<int>();
int last = 0;
foreach (var cur in weights)
{
last += cur;
cumulativeWeight.Add(last);
}
int choice = rnd.Next(last);
int i = 0;
foreach (var cur in choices)
{
if (choice < cumulativeWeight[i])
{
return cur;
}
i++;
}
return null;
}
}
Added to my code:
using UnityEngine;
using System.Linq;
using System.Collections.Generic;
public class GroundTile : MonoBehaviour
{
GroundSpawner groundSpawner;
public GameObject player;
private bool doDoubleSpawn;
private int chanceForDoubleSpawn = 45;
void Start()
{
groundSpawner = GameObject.FindObjectOfType<GroundSpawner>();
player = GameObject.Find("Tractor");
SpawnObstacle();
chanceForDoubleSpawn = GroundSpawner.levelObstaclesMultiplier;
}
// Spawn weight values for obstacles
private int boxWeightValue = 40;
private int antitankWeightValue = 40;
private int barricadeWeightValue = 40;
private int wheelsWeightValue = 40;
private int molotovItemWeightValue = 5;
// Prefabs
public GameObject obstaclePrefab;
public GameObject boxPrefab;
public GameObject antitankPrefab;
public GameObject barricadePrefab;
public GameObject wheelsPrefab;
public GameObject tankLevel1Prefab;
public GameObject molotovItemPrefab;
// Destroy if player too far away
void Update()
{
if(transform.position.z < player.transform.position.z - 30)
{
Destroy(gameObject);
}
}
}
static class RandomUtils
{
public static string Choice(this Random rnd, IEnumerable<string> choices, IEnumerable<int> weights)
{
var cumulativeWeight = new List<int>();
int last = 0;
foreach (var cur in weights)
{
last += cur;
cumulativeWeight.Add(last);
}
int choice = rnd.Next(last);
int i = 0;
foreach (var cur in choices)
{
if (choice < cumulativeWeight[i])
{
return cur;
}
i++;
}
return null;
}
}
But it gives me an error:
Assets\Scripts\GroundGenerator\GroundTile.cs(61,30): error CS0721: 'Random': static types cannot be used as parameters
How do I fix this? Maybe there is another way to write this function?
UPD: code that instantiate GroundTile:
using UnityEngine;
public class GroundSpawner : MonoBehaviour
{
public GameObject groundTile;
public GameObject groundTileEnd;
public GameObject player;
Vector3 nextSpawnPoint;
private int numOfTiles = 10;
private int plusTiles = 5;
private int count = 0;
public static int level = 1;
public static int levelObstaclesMultiplier = 45;
// Weight values for tanks and items
public static int tankWeightValue = 100;
public static int molotovItemWeightValue = 10;
public static int molotovItemWeightValuePlus = 3;
public void SpawnTile()
{
GameObject temp = Instantiate(groundTile, nextSpawnPoint, Quaternion.identity);
nextSpawnPoint = temp.transform.GetChild(1).transform.position;
}
public void SpawnEndTile()
{
GameObject temp = Instantiate(groundTileEnd, nextSpawnPoint, Quaternion.identity);
nextSpawnPoint = temp.transform.GetChild(1).transform.position;
}
void Start()
{
for (int i = 0; i < 10; i++)
{
SpawnTile();
}
SpawnEndTile();
InvokeRepeating("Spawn", 1.5f, 1.5f);
}
public void Spawn()
{
if (Time.timeScale != 0 && PlayerController.forwardSpeed != 0)
{
if (count != numOfTiles)
{
SpawnTile();
count += 1;
}
else
{
SpawnEndTile();
numOfTiles += plusTiles;
count = 0;
if (levelObstaclesMultiplier <= 65)
{
levelObstaclesMultiplier += 1;
}
}
}
}
}
This code seems to have been written for C#'s System.Random rather than the Unity-specific UnityEngine.Random class. You can resolve the error by specifying System.Random in the parameters:
public static string Choice(this System.Random rnd, IEnumerable<string> choices, IEnumerable<int> weights)
On the parameters, just replace "Random" with "System.Random", the error is because it thinks you're using UnityEngine.Random, which is a static type.
public static string Choice(this System.Random rnd, IEnumerable<string> choices, IEnumerable<int> weights)

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++;
}}

Error CS1501: No overload for method `NewDeck' takes `0' arguments (CS1501)

I am attempting to create a function that will create a set of cards
that can be randomly input into a list, but despite researching the solution
I can not figure out what I need to place in the parentheses when I called my
function, and when I return its variable.
using System;
using System.Collections.Generic;
using System.Text;
namespace BlackJackGameX
{
public class Deck
{
Random rNumber = new Random();
List<Card> Cards;
List<Card> ShuffledDeck;
public int iValue1 = 11;
public int iValue2 = 2;
public int iValue3 = 3;
public int iValue4 = 4;
public int iValue5 = 5;
public int iValue6 = 6;
public int iValue7 = 7;
public int iValue8 = 8;
public int iValue9 = 9;
public int iValue10 = 10;
public int iValue11 = 10;
public int iValue12 = 10;
public int iValue13 = 10;
I can not figure out what I need to put in the NewDeck parentheses.
public Deck()
{
Cards = NewDeck();
}
public void Shuffle()
{
for (int i = 0; i <= 51; ++i)
{
int c = rNumber.Next (1, 53);
ShuffledDeck.Add(Cards[c]);
}
}
private List<Card> NewDeck(Suit CardSuit, FaceValue CardValue, int iValue)
{
var AllSuits = new Suit[]
{
Suit.Spades,
Suit.Hearts,
Suit.Clubs,
Suit.Diamonds
};
var AllFaces = new FaceValue[]
{
FaceValue.Ace,
FaceValue.Two,
FaceValue.Three,
FaceValue.Four,
FaceValue.Five,
FaceValue.Six,
FaceValue.Seven,
FaceValue.Eight,
FaceValue.Nine,
FaceValue.Ten,
FaceValue.Jack,
FaceValue.Queen,
FaceValue.King
};
var AllValues = new int[]
{
iValue1,
iValue2,
iValue3,
iValue4,
iValue5,
iValue6,
iValue7,
iValue8,
iValue9,
iValue10,
iValue11,
iValue12,
iValue13
};
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 12; j++)
{
Card newCard = new Card(AllSuits[i], AllFaces[j], AllValues[j]);
}
}
I can not figure out what I need to put in the NewDeck parentheses
return NewDeck ();
}
public void Print()
{
Console.WriteLine(ShuffledDeck[1].CardValue);
Console.ReadLine();
}
}
}
As the signature of the method in question is:
private List<Card> NewDeck(Suit CardSuit, FaceValue CardValue, int iValue)
you will need to pass in values like the following:
return NewDeck(Suit.Spades, FaceValue.Ace, iValue1);
As Oren has said, inside the NewDeck method you do not use these values. Having the signature like this should also be OK:
private List<Card> NewDeck()

Categories