Get height of UI text element not correct Unity - c#

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 :)

Related

Network transform synchronization between players does not work

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.

JsonConvert.DeserializeObject loading data types but not data values

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

Playing specific sounds when an object is revealed

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

Convert string to color for objects

I am wondering how to convert string to a colour I have already set in c#? I have a class which sets a colour from a list and the colour variable name is set as a string. I have objects set as the colour but I am wondering how to set the colours using a colour converter for other objects, I realise this description is poor so hopefully my image will help explain more. Also hopefully someone can help me :)
Image 1 is my current output
Image 1
I want the colours under the "Zone legend" to be the same as the "Sequence Stratigraphy"
My Code for the colour setting of the sequence straigraphy is below along with my code for the zone legend
Sequence Stratigraphy Colours
internal static class ZoneColorizer
{
public static void Colorize(ZoneDto[] zones)
{
Color[] colorsToChooseFrom = new Color[] { Colors.DarkSlateGray, Colors.DarkBlue, Colors.DarkRed, Colors.DarkCyan, Colors.DarkGoldenrod, Colors.DarkGreen, Colors.DarkMagenta };
byte colorIndex = 0;
foreach (var zone in zones)
{
var color = colorsToChooseFrom[colorIndex];
var zoneColor = Color.FromArgb(128, color.R, color.G, color.B);
zone.ColourCode = zoneColor.ToString();
colorIndex++;
byte subzoneNumber = 50;
byte totalSubZones = (byte)zone.Subzones.LongLength;
byte multipler = (byte)(200 / totalSubZones);
foreach (var subzone in zone.Subzones)
{
var subZoneColor = Color.FromArgb(subzoneNumber, color.R, color.G, color.B);
subzone.ColourCode = subZoneColor.ToString();
subzoneNumber+= multipler;
}
}
}
}
Zone Legend code
private List<Color> colours;
public ObservableCollection<string> Zones { get; set; }
public LegendControl()
{
colours = new List<Color>() { Colors.DarkSlateGray, Colors.DarkBlue, Colors.DarkRed, Colors.DarkCyan, Colors.DarkGoldenrod, Colors.DarkGreen, Colors.DarkMagenta };
InitializeComponent();
Zones = new ObservableCollection<string>();
DataContext = Zones;
}
public void Bind(ZoneDto[] zones)
{
int zoneNumber = 0;
int rowNumber = 0;
byte subzoneNumber = 0;
byte totalsubZones = 0;
Zones.Clear();
foreach (var zone in zones)
{
Color zoneColor = GetColour(zoneNumber);
var zonerectangle = CreateZoneRectangle(zone, rowNumber, zoneColor);
Grid1.Children.Add(zonerectangle);
var zoneName = CreateZoneName(zone, rowNumber);
Grid1.Children.Add(zoneName);
zoneNumber++;
foreach (var subzone in zone.Subzones)
{
totalsubZones++;
Grid1.RowDefinitions.Add(new RowDefinition());
Color subzoneColor = GetGradeColour(subzoneNumber, totalsubZones, zoneColor);
var subzoneRectangle = CreateSubZoneRectangle(subzone, rowNumber, subzoneColor);
Grid1.Children.Add(subzoneRectangle);
var subzoneName = CreateSubZoneName(subzone, rowNumber);
Grid1.Children.Add(subzoneName);
subzoneNumber++;
rowNumber++;
}
}
}
private Rectangle CreateZoneRectangle(ZoneDto zone, int rowNumber, Color zoneColour)
{
var rectangle = new Rectangle
{
Fill = new SolidColorBrush(zoneColour),
Margin = new Thickness(2)
};
int rowSpan = 0;
foreach (var subzone in zone.Subzones)
{
rowSpan++;
}
rectangle.SetValue(Grid.RowProperty, rowNumber);
rectangle.SetValue(Grid.ColumnProperty, 0);
rectangle.SetValue(Grid.RowSpanProperty, rowSpan);
return rectangle;
}
private TextBlock CreateZoneName(ZoneDto zone, int rowNumber)
{
Zones.Clear();
var textblock = new TextBlock
{
Text = zone.Name,
RenderTransformOrigin = new Point(0.5, 0.5),
LayoutTransform = new RotateTransform(270),
VerticalAlignment = System.Windows.VerticalAlignment.Center,
HorizontalAlignment = System.Windows.HorizontalAlignment.Center
};
int rowSpan = 0;
foreach (var subzon in zone.Subzones)
{
rowSpan++;
}
textblock.SetValue(Grid.RowProperty, rowNumber);
textblock.SetValue(Grid.ColumnProperty, 0);
textblock.SetValue(Grid.RowSpanProperty, rowSpan);
return textblock;
}
private Rectangle CreateSubZoneRectangle(ZoneDto subzone, int rowNumber, Color subzoneColor)
{
var rectangle = new Rectangle
{
Fill = new SolidColorBrush(subzoneColor),
Margin = new Thickness(2)
};
rectangle.SetValue(Grid.RowProperty, rowNumber);
rectangle.SetValue(Grid.ColumnProperty, 1);
return rectangle;
}
private TextBlock CreateSubZoneName(ZoneDto subzone, int rowNumber)
{
var textblock = new TextBlock
{
Text = subzone.Name,
VerticalAlignment = System.Windows.VerticalAlignment.Center,
HorizontalAlignment = System.Windows.HorizontalAlignment.Center
};
textblock.SetValue(Grid.RowProperty, rowNumber);
textblock.SetValue(Grid.ColumnProperty, 1);
return textblock;
}
private Color GetColour(int zoneNumber)
{
var numOfColours = colours.Count;
if (zoneNumber >= numOfColours)
{
return colours[zoneNumber % numOfColours];
}
return colours[zoneNumber];
}
private Color GetGradeColour(byte subzoneNumber, byte totalsubZones, Color zoneColour)
{
byte multipler = (byte)(200 / totalsubZones);
byte a = (byte)((subzoneNumber + 1) * multipler);
return Color.FromArgb(a, zoneColour.R, zoneColour.G, zoneColour.B);
}
the code for the ZoneDto
public class GridDataDto
{
public WellDto[] Wells { get; set; }
public ZoneDto[] Zones { get; set; }
public string[] Facies { get; set; }
public CellDto MinLimits { get; set; }
public CellDto MaxLimits { get; set; }
}
public class ZoneDto
{
public string Name { get; set; }
public ZoneDto[] Subzones { get; set; }
public int MinK { get; set; }
public int MaxK { get; set; }
public string ColourCode { get; set; }
}
public class WellDto
{
public string Name { get; set; }
public double X { get; set; }
public double Y { get; set; }
}
public class CellDto
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public int I { get; set; }
public int J { get; set; }
public int K { get; set; }
}
EDIT: Seems there is already a built in method for this ColorConverter.ConvertFromString https://msdn.microsoft.com/en-us/library/system.windows.media.colorconverter.convertfromstring(v=vs.110).aspx
Here's the old code anyway -
The System.Windows.Media.Color ToString() method returns a hex string of the aRGB values that looks like this: #80C8DCF0 you can just split the bytes out and create a new color:
static Color FromString(string colorString)
{
byte a = Convert.ToByte(colorString.Substring(1, 2), 16);
byte r = Convert.ToByte(colorString.Substring(3, 2), 16);
byte g = Convert.ToByte(colorString.Substring(5, 2), 16);
byte b = Convert.ToByte(colorString.Substring(7, 2), 16);
return Color.FromArgb(a, r, g, b);
}
I could be reading your question wrong but if you just want the legend to share the same colours as the "Sequence Stratigraphy" could you not just use the ZoneColorizer's Colorize method on the ZoneDto[] object in your zone legend code's Bind method?

Custom List Box (or) custom Panel in windows form

im trying to create a facebook application, to display timeline and other messages
i need to customize the list box , to display Image of the sender, and the name of the sender in bold as heading and message content in a single list item.
i dont know custom panel, how to use that...
like this...
thanks in advance....
I've tried writing this to let you see how a custom panel looks like (:), this is not a complete list control and need to be extended more but it meets most of your demands. I think this is a good example for you and helps you get started so that you can build your own custom control easily:
public class ListPanel : Panel
{
public ListPanel()
{
AutoScroll = true;
BorderStyle = BorderStyle.FixedSingle;
}
private List<ListPanelItem> items = new List<ListPanelItem>();
public void AddItem(ListPanelItem item)
{
item.Index = items.Count;
items.Add(item);
Controls.Add(item);
item.BringToFront();
item.Click += ItemClicked;
}
public int SelectedIndex { get; set; }
public ListPanelItem SelectedItem { get; set; }
private void ItemClicked(object sender, EventArgs e)
{
ListPanelItem item = sender as ListPanelItem;
if (SelectedItem != null) SelectedItem.Selected = false;
SelectedItem = item;
SelectedIndex = item.Index;
item.Selected = true;
if (ItemClick != null) ItemClick(this, new ItemClickEventArgs() {Item = item});
}
public class ItemClickEventArgs : EventArgs
{
public ListPanelItem Item { get; set; }
}
public delegate void ItemClickEventHandler(object sender, ItemClickEventArgs e);
public event ItemClickEventHandler ItemClick;
}
//Here is the class for ListPanelItem
public class ListPanelItem : Panel
{
public ListPanelItem()
{
DoubleBuffered = true;
ImageSize = new Size(100, 100);
CaptionColor = Color.Blue;
ContentColor = Color.Green;
CaptionFont = new Font(Font.FontFamily, 13, FontStyle.Bold | FontStyle.Underline);
ContentFont = new Font(Font.FontFamily, 10, FontStyle.Regular);
Dock = DockStyle.Top;
SelectedColor = Color.Orange;
HoverColor = Color.Yellow;
Caption = "";
Content = "";
}
private bool selected;
public Size ImageSize { get; set; }
public Image Image { get; set; }
public string Caption { get; set; }
public string Content { get; set; }
public Color CaptionColor { get; set; }
public Color ContentColor { get; set; }
public Font CaptionFont { get; set; }
public Font ContentFont { get; set; }
public int Index { get; set; }
public bool Selected
{
get { return selected; }
set
{
selected = value;
Invalidate();
}
}
public Color SelectedColor { get; set; }
public Color HoverColor { get; set; }
protected override void OnPaint(PaintEventArgs e)
{
Color color1 = mouseOver ? Color.FromArgb(0, HoverColor) : Color.FromArgb(0, SelectedColor);
Color color2 = mouseOver ? HoverColor : SelectedColor;
Rectangle actualRect = new Rectangle(ClientRectangle.Left, ClientRectangle.Top, ClientRectangle.Width, ClientRectangle.Height - 2);
using (System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(ClientRectangle, color1, color2, 90))
{
if (mouseOver)
{
e.Graphics.FillRectangle(brush, actualRect);
}
else if (Selected)
{
e.Graphics.FillRectangle(brush, actualRect);
}
}
if (Image != null)
{
e.Graphics.DrawImage(Image, new Rectangle(new Point(5, 5), ImageSize));
}
//Draw caption
StringFormat sf = new StringFormat() { LineAlignment = StringAlignment.Center};
e.Graphics.DrawString(Caption, CaptionFont, new SolidBrush(CaptionColor), new RectangleF(ImageSize.Width + 10, 5, Width - ImageSize.Width - 10, CaptionFont.SizeInPoints * 1.5f), sf);
//Draw content
int textWidth = Width - ImageSize.Width - 10;
SizeF textSize = e.Graphics.MeasureString(Content, ContentFont);
float textHeight = (textSize.Width / textWidth) * textSize.Height + textSize.Height;
int dynamicHeight = (int)(CaptionFont.SizeInPoints * 1.5) + (int)textHeight + 1;
if (Height != dynamicHeight)
{
Height = dynamicHeight > ImageSize.Height + 10 ? dynamicHeight : ImageSize.Height + 10;
}
e.Graphics.DrawString(Content, ContentFont, new SolidBrush(ContentColor), new RectangleF(ImageSize.Width + 10, CaptionFont.SizeInPoints * 1.5f + 5, Width - ImageSize.Width - 10, textHeight));
e.Graphics.DrawLine(Pens.Silver, new Point(ClientRectangle.Left, ClientRectangle.Bottom-1), new Point(ClientRectangle.Right, ClientRectangle.Bottom-1));
base.OnPaint(e);
}
bool mouseOver;
protected override void OnMouseEnter(EventArgs e)
{
mouseOver = true;
base.OnMouseEnter(e);
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
mouseOver = false;
base.OnMouseLeave(e);
Invalidate();
}
}
The code has not been optimized, such as some of code can be done outside the OnPaint method but I keep it in there for simplicity.
Here is how my list control (or listbox) looks:

Categories