This is full code, but smth is wrong so nothing works. I have tried a few options, but it is just one thanks did not have any errors (in visual studio). Please, help to fix it.
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using Unity.VisualScripting;
using UnityEditor;
using UnityEditor.TerrainTools;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerNetwork : NetworkBehaviour
{
private readonly NetworkVariable<PlayerNetworkData> _netState = new(writePerm: NetworkVariableWritePermission.Owner);
private Vector3 _posVel;
private Vector3 _rotVel;
private Vector3 _scaVel;
#region Values
[SerializeField] private float _cheapInterpolationTime = 0.1f;
[Header("Position")]
[SerializeField] private bool _xPos;
[SerializeField] private bool _yPos;
[SerializeField] private bool _zPos;
[Header("Rotation")]
[SerializeField] private bool _xRot;
[SerializeField] private bool _yRot;
[SerializeField] private bool _zRot;
[Header("Scale")]
[SerializeField] private bool _xSca;
[SerializeField] private bool _ySca;
[SerializeField] private bool _zSca;
#endregion
void Update()
{
if (IsOwner)
{
if (_xPos) { _netState.Value = new PlayerNetworkData() { PositionX = transform.position.x }; }
if (_yPos) { _netState.Value = new PlayerNetworkData() { PositionY = transform.position.y }; }
if (_zPos) { _netState.Value = new PlayerNetworkData() { PositionZ = transform.position.z }; }
if (_xRot) { _netState.Value = new PlayerNetworkData() { RotationX = transform.rotation.eulerAngles.x }; }
if (_yRot) { _netState.Value = new PlayerNetworkData() { RotationY = transform.rotation.eulerAngles.y }; }
if (_zRot) { _netState.Value = new PlayerNetworkData() { RotationZ = transform.rotation.eulerAngles.z }; }
if (_xSca) { _netState.Value = new PlayerNetworkData() { ScaleX = transform.localScale.x }; }
if (_ySca) { _netState.Value = new PlayerNetworkData() { ScaleY = transform.localScale.y }; }
if (_zSca) { _netState.Value = new PlayerNetworkData() { ScaleZ = transform.localScale.z }; }
}
else
{
Vector3 targetPos = new Vector3(_netState.Value.PositionX, _netState.Value.PositionY, _netState.Value.PositionZ);
transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref _posVel, _cheapInterpolationTime);
Quaternion targetRot = new Quaternion(_netState.Value.RotationX, _netState.Value.RotationY, _netState.Value.RotationZ, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, _cheapInterpolationTime);
Vector3 targetSca = new Vector3(_netState.Value.ScaleX, _netState.Value.ScaleY, _netState.Value.ScaleZ);
transform.position = Vector3.SmoothDamp(transform.localScale, targetSca, ref _scaVel, _cheapInterpolationTime);
}
}
struct PlayerNetworkData : INetworkSerializable
{
float _xPos, _yPos, _zPos, _xRot, _yRot, _zRot, _xSca, _ySca, _zSca;
#region Variables
internal float PositionX
{
get => _xPos;
set => _xPos = value;
}
internal float PositionY
{
get => _yPos;
set => _yPos = value;
}
internal float PositionZ
{
get => _zPos;
set => _zPos = value;
}
internal float RotationX
{
get => _xRot;
set => _xRot = value;
}
internal float RotationY
{
get => _yRot;
set => _yPos = value;
}
internal float RotationZ
{
get => _zRot;
set => _zRot = value;
}
internal float ScaleX
{
get => _xSca;
set => _xSca = value;
}
internal float ScaleY
{
get => _ySca;
set => _ySca = value;
}
internal float ScaleZ
{
get => _zSca;
set => _zSca = value;
}
#endregion
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref _xPos);
serializer.SerializeValue(ref _yPos);
serializer.SerializeValue(ref _zPos);
serializer.SerializeValue(ref _xRot);
serializer.SerializeValue(ref _yRot);
serializer.SerializeValue(ref _zRot);
serializer.SerializeValue(ref _xSca);
serializer.SerializeValue(ref _ySca);
serializer.SerializeValue(ref _zSca);
}
}
}
I have tried to do it with more economical options, but it just does not work.
Thanks for your help.
Also I do not know why does it say that i must write more details, even though I have already writen some text.
Related
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);
}
}
I am working on a project where i turn a DJI drone into a Advanced UAV from call of duty and I'm using unity for it with C# as a client and Python as a server. I am having trouble implementing what i want the code to do.
Basically I want to parse three sets of arrays. each array is corresponding to a cube game object. Based on each game object, I want it to read the correct MQTT messages and assign the array as the transport.position of the current game object based on the game objects name.
My MQTT messages are displaying over console and my code doesn't have any errors as it runs but the blocks don't stay in place rather spawn in and out of location.
Before I added the drone and object location delegates everything spawned fine. where did i go wrong? Posting the code i have below so far. I guess I'm trying to learn where I messed up so I can formulate a proper solution. I am doing this so I can showcase an ability to solve the problem but I'm the only programmer I know so I have no idea what I'm doing wrong or what section of the code I'm messing up on other then I feel like I'm making something redundant.
edit
I think i might have to create pre fabs for each object i anticipate on the field, from there i need to create classes for those objects with get and set methods. I need to also create the script over again for each object.
```lang-csharp
public void Update()
{
while (!_messageQueue.IsEmpty)
{
string message;
if (_messageQueue.TryDequeue(out message))
{
_messageDelegate(message);
}
else
{
break;
}
}
while (!_droneLocationQueue.IsEmpty)
{
string droneLocation;
if (_droneLocationQueue.TryDequeue(out droneLocation))
{
_messageDelegate2(droneLocation);
}
else
{
break;
}
}
while (!_objectLocationQueue.IsEmpty)
{
string objectLocation;
if (_objectLocationQueue.TryDequeue(out objectLocation))
{
_messageDelegate3(objectLocation);
}
else
{
break;
}
}
}
```
```lang-csharp
private void HandleMessage(string message)
{
if (LarTarget.name == GameObject.Find("LarTarget").ToString())
{
var splittedStrings = message.Split(' ');
if (splittedStrings.Length != 3) return;
latitude = float.Parse(splittedStrings[0]);
longitude = float.Parse(splittedStrings[1]);
altitude = float.Parse(splittedStrings[2]);
LarTarget.transform.position = new Vector3(latitude, longitude, altitude);
}
else if(objectLocationTarget.name == GameObject.Find("objectLocationTarget").ToString())
{
var splittedStrings = message.Split(' ');
if (splittedStrings.Length != 3) return;
latitude1 = float.Parse(splittedStrings[0]);
longitude1 = float.Parse(splittedStrings[1]);
altitude1 = float.Parse(splittedStrings[2]);
objectLocationTarget.transform.position = new Vector3(latitude1, longitude1, altitude1);
}
else {
var splittedStrings = message.Split(' ');
if (splittedStrings.Length != 3) return;
latitude2 = float.Parse(splittedStrings[0]);
longitude2 = float.Parse(splittedStrings[1]);
altitude2 = float.Parse(splittedStrings[2]);
droneTarget.transform.position = new Vector3(latitude2, longitude2, altitude2);
}
}
```
full code in this block
```lang-csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Collections.Concurrent;
using System.Threading;
using NetMQ;
using NetMQ.Sockets;
public class NetMqListener
{
private readonly Thread _listenerWorker;
private readonly Thread _listenerWorker2;
private readonly Thread _listenerWorker3;
private bool _listenerCancelled;
public delegate void MessageDelegate(string message);
public delegate void MessageDelegate2(string droneLocation);
public delegate void MessageDelegate3(string objectLocation);
private readonly MessageDelegate _messageDelegate;
private readonly MessageDelegate2 _messageDelegate2;
private readonly MessageDelegate3 _messageDelegate3;
private readonly ConcurrentQueue<string> _messageQueue = new ConcurrentQueue<string>();
private readonly ConcurrentQueue<string> _droneLocationQueue = new ConcurrentQueue<string>();
private readonly ConcurrentQueue<string> _objectLocationQueue = new ConcurrentQueue<string>();
private void ListenerWork()
{
AsyncIO.ForceDotNet.Force();
using (var subSocket = new SubscriberSocket())
{
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect("tcp://192.168.1.5:12345");
subSocket.Subscribe("");
while (!_listenerCancelled)
{
string frameString;
if (!subSocket.TryReceiveFrameString(out frameString)) continue;
Debug.Log(frameString);
_messageQueue.Enqueue(frameString);
}
subSocket.Close();
}
NetMQConfig.Cleanup();
}
private void ListenerWork2()
{
AsyncIO.ForceDotNet.Force();
using (var subSocket = new SubscriberSocket())
{
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect("tcp://192.168.1.5:12345");
subSocket.Subscribe("");
while (!_listenerCancelled)
{
string frameString2;
if (!subSocket.TryReceiveFrameString(out frameString2)) continue;
Debug.Log(frameString2);
_objectLocationQueue.Enqueue(frameString2);
}
subSocket.Close();
}
NetMQConfig.Cleanup();
}
private void ListenerWork3()
{
AsyncIO.ForceDotNet.Force();
using (var subSocket = new SubscriberSocket())
{
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect("tcp://192.168.1.5:12345");
subSocket.Subscribe("");
while (!_listenerCancelled)
{
string frameString3;
if (!subSocket.TryReceiveFrameString(out frameString3)) continue;
Debug.Log(frameString3);
_droneLocationQueue.Enqueue(frameString3);
}
subSocket.Close();
}
NetMQConfig.Cleanup();
}
public void Update()
{
while (!_messageQueue.IsEmpty)
{
string message;
if (_messageQueue.TryDequeue(out message))
{
_messageDelegate(message);
}
else
{
break;
}
}
while (!_droneLocationQueue.IsEmpty)
{
string droneLocation;
if (_droneLocationQueue.TryDequeue(out droneLocation))
{
_messageDelegate2(droneLocation);
}
else
{
break;
}
}
while (!_objectLocationQueue.IsEmpty)
{
string objectLocation;
if (_objectLocationQueue.TryDequeue(out objectLocation))
{
_messageDelegate3(objectLocation);
}
else
{
break;
}
}
}
public NetMqListener(MessageDelegate messageDelegate, MessageDelegate2 messageDelegate2, MessageDelegate3 messageDelegate3)
{
_messageDelegate = messageDelegate;
_messageDelegate2 = messageDelegate2;
_messageDelegate3 = messageDelegate3;
_listenerWorker = new Thread(ListenerWork);
_listenerWorker2 = new Thread(ListenerWork2);
_listenerWorker3 = new Thread(ListenerWork3);
}
public void Start()
{
_listenerCancelled = false;
_listenerWorker.Start();
_listenerWorker2.Start();
_listenerWorker3.Start();
}
public void Stop()
{
_listenerCancelled = true;
_listenerWorker.Join();
_listenerWorker2.Join();
_listenerWorker3.Join();
}
}
public class LocativeTargetClient : MonoBehaviour
{
[Header("Google Maps Coordinates")]
public float latitude;
public float latitude1;
public float latitude2;
public float longitude;
public float longitude1;
public float longitude2;
public float altitude;
public float altitude1;
public float altitude2;
public GameObject LarTarget;
public GameObject objectLocationTarget;
public GameObject droneTarget;
//[Header("Enable")]
//public float MaximumDistance=1000;
private double raioTerra = 6372797.560856f;
private readonly Thread _listenerWorker;
private readonly Thread _listenerWorker2;
private readonly Thread _listenerWorker3;
private NetMqListener _netMqListener;
private NetMqListener _netMqListener2;
private NetMqListener _netMqListener3;
private bool _listenerCancelled;
public delegate void MessageDelegate(string message);
public delegate void MessageDelegate2(string droneLocation);
public delegate void MessageDelegate3(string objectLocation);
private readonly MessageDelegate _messageDelegate;
private readonly MessageDelegate2 _messageDelegate2;
private readonly MessageDelegate3 _messageDelegate3;
private readonly ConcurrentQueue<string> _messageQueue = new ConcurrentQueue<string>();
private readonly ConcurrentQueue<string> _droneLocationQueue = new ConcurrentQueue<string>();
private readonly ConcurrentQueue<string> _objectLocationQueue = new ConcurrentQueue<string>();
private void ListenerWork()
{
AsyncIO.ForceDotNet.Force();
using (var subSocket = new SubscriberSocket())
{
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect("tcp://192.168.200.245:12345");
subSocket.Subscribe("");
while (!_listenerCancelled)
{
string frameString;
if (!subSocket.TryReceiveFrameString(out frameString)) continue;
Debug.Log(frameString);
_messageQueue.Enqueue(frameString);
}
subSocket.Close();
}
NetMQConfig.Cleanup();
}
private void ListenerWork2()
{
AsyncIO.ForceDotNet.Force();
using (var subSocket = new SubscriberSocket())
{
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect("tcp://192.168.200.245:12345");
subSocket.Subscribe("");
while (!_listenerCancelled)
{
string frameString2;
if (!subSocket.TryReceiveFrameString(out frameString2)) continue;
Debug.Log(frameString2);
_droneLocationQueue.Enqueue(frameString2);
}
subSocket.Close();
}
NetMQConfig.Cleanup();
}
private void ListenerWork3()
{
AsyncIO.ForceDotNet.Force();
using (var subSocket = new SubscriberSocket())
{
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect("tcp://192.168.200.245:12345");
subSocket.Subscribe("");
while (!_listenerCancelled)
{
string frameString3;
if (!subSocket.TryReceiveFrameString(out frameString3)) continue;
Debug.Log(frameString3);
_objectLocationQueue.Enqueue(frameString3);
}
subSocket.Close();
}
NetMQConfig.Cleanup();
}
private void Start()
{
//print(raioTerra + " " + longitude);
_netMqListener = new NetMqListener(HandleMessage);
_netMqListener2 = new NetMqListener(HandleDroneLocation);
_netMqListener3 = new NetMqListener(HandleObjectLocation);
_netMqListener.Start();
_netMqListener2.Start();
_netMqListener3.Start();
}
private void HandleMessage(string message)
{
if (LarTarget.name == GameObject.Find("LarTarget").ToString())
{
var splittedStrings = message.Split(' ');
if (splittedStrings.Length != 3) return;
latitude = float.Parse(splittedStrings[0]);
longitude = float.Parse(splittedStrings[1]);
altitude = float.Parse(splittedStrings[2]);
LarTarget.transform.position = new Vector3(latitude, longitude, altitude);
}
else if(objectLocationTarget.name == GameObject.Find("objectLocationTarget").ToString())
{
var splittedStrings = message.Split(' ');
if (splittedStrings.Length != 3) return;
latitude1 = float.Parse(splittedStrings[0]);
longitude1 = float.Parse(splittedStrings[1]);
altitude1 = float.Parse(splittedStrings[2]);
objectLocationTarget.transform.position = new Vector3(latitude1, longitude1, altitude1);
}
else {
var splittedStrings = message.Split(' ');
if (splittedStrings.Length != 3) return;
latitude2 = float.Parse(splittedStrings[0]);
longitude2 = float.Parse(splittedStrings[1]);
altitude2 = float.Parse(splittedStrings[2]);
droneTarget.transform.position = new Vector3(latitude2, longitude2, altitude2);
}
}
private void HandleObjectLocation(string objectLocation)
{
if (objectLocationTarget.name == GameObject.Find("objectLocationTarget").ToString()){
var splittedStrings = objectLocation.Split(' ');
if (splittedStrings.Length != 3) return;
latitude1 = float.Parse(splittedStrings[0]);
longitude1 = float.Parse(splittedStrings[1]);
altitude1 = float.Parse(splittedStrings[2]);
objectLocationTarget.transform.position = new Vector3(latitude1, longitude1, altitude1);
}
else if(LarTarget.name == GameObject.Find("LarTarget").ToString())
{
var splittedStrings = objectLocation.Split(' ');
if (splittedStrings.Length != 3) return;
latitude = float.Parse(splittedStrings[0]);
longitude = float.Parse(splittedStrings[1]);
altitude = float.Parse(splittedStrings[2]);
LarTarget.transform.position = new Vector3(latitude, longitude, altitude);
}
else {
var splittedStrings = objectLocation.Split(' ');
if (splittedStrings.Length != 3) return;
latitude2 = float.Parse(splittedStrings[0]);
longitude2 = float.Parse(splittedStrings[1]);
altitude2 = float.Parse(splittedStrings[2]);
droneTarget.transform.position = new Vector3(latitude2, longitude2, altitude2);
}
}
private void HandleDroneLocation(string droneLocation)
{
if (droneTarget.name == GameObject.Find("droneTarget").ToString()){
var splittedStrings = droneLocation.Split(' ');
if (splittedStrings.Length != 3) return;
latitude2 = float.Parse(splittedStrings[0]);
longitude2 = float.Parse(splittedStrings[1]);
altitude2 = float.Parse(splittedStrings[2]);
droneTarget.transform.position = new Vector3(latitude2, longitude2, altitude2);
}
else if(LarTarget.name == GameObject.Find("LarTarget").ToString())
{
var splittedStrings = droneLocation.Split(' ');
if (splittedStrings.Length != 3) return;
latitude = float.Parse(splittedStrings[0]);
longitude = float.Parse(splittedStrings[1]);
altitude = float.Parse(splittedStrings[2]);
LarTarget.transform.position = new Vector3(latitude, longitude, altitude);
}
else
{
var splittedStrings = droneLocation.Split(' ');
if (splittedStrings.Length != 3) return;
latitude1 = float.Parse(splittedStrings[0]);
longitude1 = float.Parse(splittedStrings[1]);
altitude1 = float.Parse(splittedStrings[2]);
objectLocationTarget.transform.position = new Vector3(latitude1, longitude1, altitude1);
}
}
private void Update()
{
Vector3 coord = calculaPosCoordCam();
Vector3 coord2 = calculaPosCoordCam1();
Vector3 coord3 = calculaPosCoordCam2();
LarTarget.transform.position = coord;
objectLocationTarget.transform.position = coord2;
droneTarget.transform.position = coord3;
//print(coord.x +" " + coord.y + " " + coord.z);
_netMqListener.Update();
_netMqListener2.Update();
_netMqListener3.Update();
}
private void OnDestroy()
{
_netMqListener.Stop();
_netMqListener2.Stop();
_netMqListener3.Stop();
}
private Vector3 calculaPosCoordCam()
{
double dlat = latitude - LocativeGPS.Instance.latitude;
dlat = getCoordEmMetrosDeRaio(raioTerra, dlat);
double dlon = longitude - LocativeGPS.Instance.longitude;
double raioLat = Mathf.Cos((float)latitude) * raioTerra;
dlon = getCoordEmMetrosDeRaio(raioLat, dlon);
double dalt = altitude - 0.0f;// LocativeGPS.Instance.altitude;
return new Vector3((float)dlat, (float)dalt, (float)dlon);
}
private Vector3 calculaPosCoordCam1()
{
double dlat1 = latitude1 - LocativeGPS.Instance.latitude;
dlat1 = getCoordEmMetrosDeRaio(raioTerra, dlat);
double dlon1 = longitude1 - LocativeGPS.Instance.longitude;
double raioLat1 = Mathf.Cos((float)latitude1) * raioTerra;
dlon1 = getCoordEmMetrosDeRaio(raioLat1, dlon1);
double dalt1 = altitude1 - 0.0f;// LocativeGPS.Instance.altitude;
return new Vector3((float)dlat1, (float)dalt1, (float)dlon1);
}
private Vector3 calculaPosCoordCam2()
{
double dlat2 = latitude2 - LocativeGPS.Instance.latitude;
dlat2 = getCoordEmMetrosDeRaio(raioTerra, dlat2);
double dlon2 = longitude2 - LocativeGPS.Instance.longitude;
double raioLat2 = Mathf.Cos((float)latitude2) * raioTerra;
dlon2 = getCoordEmMetrosDeRaio(raioLat2, dlon2);
double dalt2 = altitude2 - 0.0f;// LocativeGPS.Instance.altitude;
return new Vector3((float)dlat2, (float)dalt2, (float)dlon2);
}
private double getCoordEmMetrosDeRaio(double raio, double angulo)
{
double metros = (raio / 180) * Mathf.PI;//
metros *= angulo;
return metros;
}
}
}
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;
}
}
}
I have some code to set a custom with for a text element and then the height gets adjusted automatically like so:
Title.SetTextContainerSize("autoH", 330);
public void SetTextContainerSize(string fit, float dimension = 0)
{
if (UIElement.GetComponent<ContentSizeFitter>() == null)
UISizeFitterComponent = UIElement.AddComponent(typeof(ContentSizeFitter)) as ContentSizeFitter;
if (fit == "autoWH")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
base.SetDimensions( RectOptions.sizeDelta);
}
else if (fit == "autoW")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
base.SetDimensions( new Vector2(RectOptions.rect.width, dimension));
}
else if (fit == "autoH")
{ //here is a problem..
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
Canvas.ForceUpdateCanvases();
Debug.Log(new Vector2(dimension, RectOptions.rect.height));
base.SetDimensions( new Vector2(dimension, RectOptions.rect.height));
}
}
Edit Added the set dimensions function
public void SetDimensions(Vector2 dimensions)
{
RectOptions.sizeDelta = dimensions;
Dimensions = dimensions; //this just sets the value of a property.
}
but when i call the function to update the text i get the following result from the Debug.Log() it says the width = 330 and the height is 2077. In this case the width is correct but the height is not even close.
See here a screenshot of the actual element and its correct height.
Edit 2 My unity version is 2018.1.3f1
what am i doing wrong when updating the actual height of the element?
If there is an completely other way to do it i am also open for complete rewrites of the current function if nessesary :)
IF something is unclear let me know so i can clarify!
Edit 3 I decided to add the full code of the classes that use the fuction and the code that calls the respective function, Maybe there is a problem that causes the error:
this is the code that calls the problametic function:
var Title = new EasyText(new Vector2(390, -20), Vector2.zero, Data.title, 30, _color: new Color(0,0,0,1));
Title.SetTextContainerSize("autoH", 330);
Main.MainCanvas.Add(Title);
var titleBottom = (Title.Dimensions.y);
Debug.Log(titleBottom);
This is the classes that are called by the above code:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
namespace Easy.UI
{
public static class EasyUISettings
{
public struct AnchorPoints
{
public static readonly Vector2 TopLeft = new Vector2(0, 1);
public static readonly Vector2 Center = new Vector2(0.5f, 0.5f);
public static readonly Vector2 CenterLeft = new Vector2(0, 0.5f);
public static readonly Vector2 CenterRight = new Vector2(1, 0.5f);
public static readonly Vector2 TopCenter = new Vector2(0.5f, 1);
public static readonly Vector2 BottomCenter = new Vector2(0.5f, 0);
}
public struct CoordinateReference
{
private CoordinateReference(int minX, int maxX, int minY, int maxY)
{
AnchorMin = new Vector2(minX, minY);
AnchorMax = new Vector2(maxX, maxY);
}
public Vector2 AnchorMin { get; set; }
public Vector2 AnchorMax { get; set; }
public static readonly CoordinateReference TopLeft = new CoordinateReference(0, 0, 1, 1);
public static readonly CoordinateReference TopRight = new CoordinateReference(1, 1, 1, 1);
public static readonly CoordinateReference BottomLeft = new CoordinateReference(0, 0, 0, 0);
public static readonly CoordinateReference BottomRight = new CoordinateReference(1, 1, 0, 0);
}
public struct TextAlignment
{
public static readonly TextAnchor TopLeft = TextAnchor.UpperLeft;
public static readonly TextAnchor TopRight = TextAnchor.UpperRight;
public static readonly TextAnchor TopCenter = TextAnchor.UpperCenter;
public static readonly TextAnchor CenterLeft = TextAnchor.MiddleLeft;
public static readonly TextAnchor CenterRight = TextAnchor.MiddleRight;
public static readonly TextAnchor CenterCenter = TextAnchor.MiddleCenter;
public static readonly TextAnchor BottomLeft = TextAnchor.LowerLeft;
public static readonly TextAnchor BottomCenter = TextAnchor.LowerCenter;
public static readonly TextAnchor BottomRight = TextAnchor.LowerRight;
}
}
public static class EasyUIHelpers
{
public static void DestroyUIElement(EasyUIELementFoundation element)
{
element.DestroyUIElement();
element = null;
}
}
public class EasyCanvas
{
private GameObject CanvasObject, Events;
private RectTransform Rect;
private Canvas CanvasScript;
private CanvasScaler Scaler;
private GraphicRaycaster Raycaster;
private StandaloneInputModule Inputs;
private List<EasyUIELementFoundation> CanvasElements;
public EasyCanvas()
{
CanvasElements = new List<EasyUIELementFoundation>();
CanvasObject = new GameObject();
CanvasObject.name = "EasyCanvas";
Rect = CanvasObject.AddComponent(typeof(RectTransform)) as RectTransform;
CanvasScript = CanvasObject.AddComponent(typeof(Canvas)) as Canvas;
Scaler = CanvasObject.AddComponent(typeof(CanvasScaler)) as CanvasScaler;
Raycaster = CanvasObject.AddComponent(typeof(GraphicRaycaster)) as GraphicRaycaster;
CanvasScript.pixelPerfect = true;
Events = new GameObject();
Events.name = "EasyEventsHandler";
Events.AddComponent(typeof(EventSystem));
Inputs = Events.AddComponent(typeof(StandaloneInputModule)) as StandaloneInputModule;
}
public EasyCanvas(string _type, Camera c) : this()
{
CanvasScript.worldCamera = c;
CanvasScript.planeDistance = 0.15f;
if (_type.Equals("Camera"))
{
CanvasScript.renderMode = RenderMode.ScreenSpaceCamera;
Scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
Scaler.referenceResolution = new Vector2(1920, 1080);
Scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
}
else if(_type.Equals("World"))
CanvasScript.renderMode = RenderMode.WorldSpace;
}
public void Add(EasyUIELementFoundation element)
{
element.AddToCanvas(CanvasScript);
CanvasElements.Add(element);
}
public void EmptyCanvas()
{
for (int i = CanvasElements.Count - 1; i >= 0 ; i--)
{
CanvasElements[i].DestroyUIElement();
CanvasElements[i] = null;
CanvasElements.RemoveAt(i);
}
}
public Vector2 GetCanvasDimensions()
{
return Rect.sizeDelta;
}
}
public abstract class EasyUIELementFoundation
{
protected GameObject UIElement;
protected RectTransform RectOptions;
public Vector2 Position { get; private set; }
public Vector2 Dimensions { get; private set; }
public Vector2 PivotPoint { get; private set; }
public EasyUISettings.CoordinateReference ReferenceCoordinates { get; private set; }
protected EasyUIELementFoundation(Vector2 _position, Vector2 _dimensions)
{
UIElement = new GameObject();
RectOptions = UIElement.AddComponent(typeof(RectTransform)) as RectTransform;
SetPivotReference(EasyUISettings.AnchorPoints.TopLeft);
SetCoordinateReference(EasyUISettings.CoordinateReference.TopLeft);
SetPosition(_position);
SetDimensions(_dimensions);
}
public void SetCoordinateReference(EasyUISettings.CoordinateReference reference)
{
RectOptions.anchorMin = reference.AnchorMin;
RectOptions.anchorMax = reference.AnchorMax;
ReferenceCoordinates = reference;
}
public void SetPivotReference(Vector2 reference)
{
RectOptions.pivot = reference;
PivotPoint = reference;
}
public void SetPosition(Vector2 pos)
{
RectOptions.anchoredPosition = pos;
Position = pos;
}
public void SetDimensions(Vector2 dimensions)
{
RectOptions.sizeDelta = dimensions;
Dimensions = dimensions;
}
public void AddToCanvas(Canvas c)
{
UIElement.transform.SetParent(c.transform, false);
}
public void DestroyUIElement()
{
Object.Destroy(UIElement);
}
}
public class EasyText : EasyUIELementFoundation
{
protected ContentSizeFitter UISizeFitterComponent;
protected Text UITextComponent;
public string Text { get; private set; }
public Color TextColor { get; private set; }
public Font TextFont { get; private set; }
public int FontSize { get; private set; }
public TextAnchor TextAlignment { get; private set; }
public EasyText(Vector2 _position = default(Vector2), Vector2 _dimensions = default(Vector2), string _text = "Base Text", int _fontSize = 15, Font _font = null, Color _color = default(Color), TextAnchor _align = default(TextAnchor)) : base(_position, _dimensions)
{
UITextComponent = UIElement.AddComponent(typeof(Text)) as Text;
SetText(_text);
SetTextSize(_fontSize);
SetFont(_font);
SetTextColor(_color);
SetTextAlignment(_align);
}
public void SetText(string text)
{
Text = text;
UITextComponent.text = Text;
}
public void SetTextSize(int size)
{
FontSize = size;
UITextComponent.fontSize = size;
}
public void SetFont(UnityEngine.Object font)
{
var ValidFont = (Font)font;
if(ValidFont != null)
{
TextFont = ValidFont;
UITextComponent.font = TextFont;
}
else
{
TextFont = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
UITextComponent.font = TextFont;
Debug.LogWarning("No font was specified using default font");
}
}
public void SetTextColor(Color color)
{
TextColor = color;
UITextComponent.color = TextColor;
}
public void SetTextAlignment(TextAnchor alignment)
{
TextAlignment = alignment;
UITextComponent.alignment = alignment;
}
public void SetTextContainerSize(string fit, float dimension = 0)
{
if (UIElement.GetComponent<ContentSizeFitter>() == null)
UISizeFitterComponent = UIElement.AddComponent(typeof(ContentSizeFitter)) as ContentSizeFitter;
if (fit == "autoWH")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
base.SetDimensions( RectOptions.sizeDelta);
}
else if (fit == "autoW")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.Unconstrained;
base.SetDimensions( new Vector2(RectOptions.rect.width, dimension));
}
else if (fit == "autoH")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.Unconstrained;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
// THIS NEEDS A FIX OMG
// LayoutRebuilder.ForceRebuildLayoutImmediate(RectOptions);
Canvas.ForceUpdateCanvases();
UISizeFitterComponent.SetLayoutVertical();
base.SetDimensions( new Vector2(dimension, RectOptions.rect.height));
}
}
public void RemoveContentSizeFitter()
{
var component = UIElement.GetComponent(typeof(ContentSizeFitter)) as ContentSizeFitter;
if(component != null)
Object.Destroy(component);
}
}
}
after spending hours upon hours trying to find a solution i finally found it..
It was actually a really stupid mistake.
Here is an explaination:
I initiated my custom UIText class in the following way:
var Title = new EasyText(new Vector2(390, -20), Vector2.zero, Data.title, 30, _color: new Color(0,0,0,1));
Notice the Vector.zero for the dimensions of the text element? yeah that is gonna cause some problems.
Because the following i did was call this, on the just created title element:
Title.SetTextContainerSize("autoH", 330);
this would call my size fitter update function see below:
public void SetTextContainerSize(string fit, float dimension = 0)
{
if (UIElement.GetComponent<ContentSizeFitter>() == null)
UISizeFitterComponent = UIElement.AddComponent(typeof(ContentSizeFitter)) as ContentSizeFitter;
if (fit == "autoWH")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
base.SetDimensions( RectOptions.sizeDelta);
}
else if (fit == "autoW")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.Unconstrained;
Canvas.ForceUpdateCanvases();
base.SetDimensions( new Vector2(RectOptions.rect.width, dimension));
}
else if (fit == "autoH")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.Unconstrained;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
Canvas.ForceUpdateCanvases();
base.SetDimensions( new Vector2(dimension, RectOptions.rect.height));
}
}
In the cases the fit value is either autoW or autoH the program will add the content size fitter but since the size of the element is 0 because of the initialization. The content size fitter is gonna expand the element to the extreme because the other size is just 0.
Then i update the canvases but this doesnt do anything because the element has a width or height of 0. Resulting in the huge numbers when getting the values back. So how to fix this?
Just make sure the element has some width or height before adding the content size fitter like so:
public void SetTextContainerSize(string fit, float dimension = 0)
{
if (UIElement.GetComponent<ContentSizeFitter>() == null)
UISizeFitterComponent = UIElement.AddComponent(typeof(ContentSizeFitter)) as ContentSizeFitter;
if (fit == "autoWH")
{
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
}
else if (fit == "autoW")
{
base.SetDimensions(new Vector2(dimension, dimension));
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.Unconstrained;
Canvas.ForceUpdateCanvases();
base.SetDimensions( new Vector2(RectOptions.rect.width, dimension));
}
else if (fit == "autoH")
{
base.SetDimensions(new Vector2(dimension, dimension));
UISizeFitterComponent.horizontalFit = ContentSizeFitter.FitMode.Unconstrained;
UISizeFitterComponent.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
Canvas.ForceUpdateCanvases();
base.SetDimensions( new Vector2(dimension, RectOptions.rect.height));
}
}
and that solved my problem. I really hope this helps anyone in the future!
If you dont understand anything, drop a comment so i can clarify my answer :)
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++;
}}