Match 2 differents object with the same instance name - c#

I would like to know if it is possible to match object with their instance name.
I got :
class AnimatedEntity : DrawableEntity
{
Animation BL { get; set; }
Animation BR { get; set; }
Animation TL { get; set; }
Animation TR { get; set; }
Animation T { get; set; }
Animation R { get; set; }
Animation L { get; set; }
Animation B { get; set; }
Orientation orientation ;
public virtual int Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
//draw depends on orientation
}
}
and
enum Orientation {
SE, SO, NE, NO,
N , E, O, S,
BL, BR, TL, TR,
T, R, L, B
}
Where Orientation is an Enum and Animation a class.
Can I call the correct Animation from the Orientation with the same name ?

Instead of storing the Animations in properties, how about using a dictionary?
Dictionary<Orientation, Animation> anim = new Dictionary<Orientation, Animation> {
{ Orientation.BL, blAnimation },
{ Orientation.BR, brAnimation },
{ Orientation.TL, tlAnimation },
{ Orientation.TR, trAnimation },
{ Orientation.T, tAnimation },
{ Orientation.R, rAnimation },
{ Orientation.L, lAnimation },
{ Orientation.B, bAnimation }
};
You can then use anim[orientation] to access the appropriate animation.

Indeed a Dictionary would be a good option. It could even have an Animation index if the animations would be set from outside:
class AnimatedEntity : DrawableEntity
{
Dictionary<Orientation, Animation> Animations { get; set; }
public AnimatedEntity()
{
Animations = new Dictionary<Orientation, Animation>();
}
public Animation this[Orientation orientation]
{
get{ return Animations[orientation]; }
set{ Animations[orientation] = value;}
}
Orientation Orientation { get; set; }
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
Animation anim = Animations[Orientation];
}
}
Would be used like:
AnimatedEntity entity = new AnimatedEntity();
entity[Orientation.B] = bAnimation;
entity[Orientation.E] = eAnimation;
entity[Orientation.SE] = seAnimation;

Related

Linking instances of two classes together

Programming newbie here and I've been breaking my head over this for several hours now.
I can make a coordinate object but then I want to make a dot object that can access the coordinate fields from a Coordinate object. How do I "link" these two classes together? And do you have any recommendations for good YouTube videos that explain what I'm missing here? Thanks!
class Coordinate
{
public int X { get; private set; } = 0;
public int Y { get; private set; } = 0;
public Coordinate(int x, int y)
{
x = X;
y = Y;
}
}
class Dot
{
public string color { get; set; }
public Dot(string color, Dot dot)
{
this.Color = color;
}
}
class Program
{
static void Main(string[] args)
{
Coordinate coor1 = new Coordinate(2, 3);
Dot dot1 = new Dot("Blue", coor1);
}
Here is what you are searching for a "linking" your classes. In object-oriented programming this is called composition.
That way you can use functionality and data of Coordinate-instance inside your Dot class.
class Coordinate
{
public int X { get; private set; }
public int Y { get; private set; }
public Coordinate(int x, int y)
{
X = x;
Y = y;
}
}
class Dot
{
public Coordinate coord { get; private set; }
public string color { get; set; }
public Dot(string color, Coordinate coord)
{
this.color = color;
this.coord = coord;
}
}
class Program
{
static void Main(string[] args)
{
Coordinate coor1 = new Coordinate(2, 3);
Dot dot1 = new Dot("Blue", coor1);
Console.WriteLine(dot1.coord.X);
}
}
Note: I also fixed possible typo in Coordinate-constructor (setting X=x and Y=y..)

Draw a shape on a canvas in a new window C#

I am looking for a way to draw a simple shape on a canvas with the shape being made in another class ShapeManager. This ShapeManager decides what shape it is and assigns a color to it coming from ColorManager.
I apologize in advance for the long code, this is my first post and I am still just learning C# and OOP in general.
Canvas Window
A window with a canvas on it (cvs_Drawing). Should place a shape it gets from CanvasManager.ShapeManager.CreateNewShape(), but throws a NullReference.
public partial class CanvasWindow : Window
{
public string CanvasName { get; set; }
public CanvasManager CanvasManager { get; set; }
public CanvasWindow(string name)
{
InitializeComponent();
CanvasManager= new CanvasManager();
CanvasName = name;
this.Title = CanvasName;
}
//Click event to draw the chosen shape on canvas
private void cvs_Drawing_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
Shape shapeDrawing = CanvasManager.ShapeManager.CreateNewShape();
Point location = e.GetPosition(cvs_Drawing);
Canvas.SetTop(shapeDrawing, location.Y);
Canvas.SetLeft(shapeDrawing, location.X);
cvs_Drawing.Children.Add(shapeDrawing);
}
//catch block here
CanvasManager
Creates CanvasWindows and provides interaction between CanvasWindow and ShapeManager. Multiple CanvasWindows is normally a possibility.
public CanvasWindow CanvasWindow { get; set; }
public MainWindow MainWindow { get; set; }
public ShapeManager ShapeManager { get; set; }
//Constructors
public CanvasManager(MainWindow w)
{
MainWindow = w;
ShapeManager = new ShapeManager(w);
}
public CanvasManager() { }
//Add a brand new canvas
public CanvasWindow CreateNewCanvas(string name)
{
CanvasWindow = new CanvasWindow(name);
return CanvasWindow;
}
ShapeManager
Creates Shapes needed for CanvasWindow
public MainWindow Window { get; set; }
public Shape NewShape { get; set; }
public ColorManager ColorManager { get; set; }
public List<string> ListShapes { get; set; } = new List<string>();
public ShapeManager(MainWindow w)
{
Window = w;
ListShapes.Add("Ellipse");
ListShapes.Add("Rectangle");
ColorManager = new ColorManager();
}
public ShapeManager() { }
#region Shape Creation
public Shape CreateNewShape()
{
Color newShapeColor = ColorManager.CreateNewColor();
if (Window.cb_Shapes.SelectedItem.ToString() == "Ellipse")
{
NewShape = new Ellipse
{
Width = Int32.Parse(Window.tb_Width.Text),
Height = Int32.Parse(Window.tb_Height.Text),
Fill = new SolidColorBrush(newShapeColor)
};
return NewShape;
}
else
{
NewShape = new Rectangle
{
Width = Int32.Parse(Window.tb_Width.Text),
Height = Int32.Parse(Window.tb_Height.Text),
Fill = new SolidColorBrush(newShapeColor)
};
return NewShape;
}
}
ColorManager
Creates the color for the shape that was created in ShapeManager.
public MainWindow Window { get; set; }
public Color NewColor { get; set; }
//Constructors
public ColorManager(MainWindow w)
{
Window = w;
}
//public ColorManager(){}
//Add new color method
public Color CreateNewColor()
{
NewColor = new Color
{
A = 255,
R = Byte.Parse(Window.tb_RedValue.Text),
G = Byte.Parse(Window.tb_GreenValue.Text),
B = Byte.Parse(Window.tb_BlueValue.Text)
};
return NewColor;
}
TL;DR. I can't create a shape on the canvas, always get a NullReference every time I click on the canvas.
Your code has an error here
public CanvasManager(){ ShapeManager = new ShapeManager(MainWindow); }
// CanvasManager.cs , Line 33
you passed MainWindow, which is null
and it comes from here
public CanvasManager CanvasManager { get; set; } = new CanvasManager();
// CanvasWindow.xaml.cs, Line 28
You can correct your code like this:
// in CanvasWindow.xaml.cs, Line 28
public CanvasWindow(string name, MainWindow mainWindow)
{
InitializeComponent();
**CanvasManager = new CanvasManager(mainWindow);**
CanvasName = name;
//ShapeManager = new ShapeManager();
this.Title = CanvasName;
...
...
...
// NewDrawingWindow.xaml.cs, Line 47
CanvasWindow canvasWindow = new CanvasWindow(tb_Drawing_Name.Text, Window);
// CanvasManager.cs, Line 38
CanvasWindow = new CanvasWindow(name, MainWindow);

Unity connect a Character Class to a UI Toggle

I am trying to build a Character Selection. When I tick a toggle, it should say "You selected class xy". I already got the active Toggle of the Toggle Group, I just do not know how to connect it to another object.
I divided my Scripts into 3 parts, Data, View and Controller.
My view:
public class ClassSelectionCommonView : MonoBehaviour
{
[SerializeField]
ToggleGroup toggleGroup; // Get the Toggle Group of the Scene
public Toggle GetActiveToggle() // Return the single active Toggle
{
return toggleGroup.ActiveToggles().FirstOrDefault();
}
}
My Data:
public class ClassSelectionCommonData : MonoBehaviour
{
public string ClassName { get; set; } // The characters stats
public float MovementSpeed { get; set; }
public float LifePoints { get; set; }
public float DamageReduction { get; set; }
public float AttackDamageMelee { get; set; }
public float AttackDamageRange { get; set; }
public float AttackSpeed { get; set; }
public float GoldFind { get; set; }
private ClassSelectionCommonData templar = new ClassAlchemist(); // Create Character Classes
private ClassSelectionCommonData inquisitor = new ClassInquisitor();
private ClassSelectionCommonData hunter = new ClassHunter();
private ClassSelectionCommonData warlord = new ClassWarlord();
private ClassSelectionCommonData bandit = new ClassBandit();
private ClassSelectionCommonData alchemist = new ClassAlchemist();
private ClassSelectionCommonData engineer = new ClassEngineer();
private ClassSelectionCommonData thief = new ClassThief();
private ClassSelectionCommonData occultist = new ClassOccultist();
}
And the Controller:
public class ClassSelectionCommonController : MonoBehaviour
{
ClassSelectionCommonData data;
ClassSelectionCommonView view;
private void Start()
{
data = GetComponent<ClassSelectionCommonData>();
view = GetComponent<ClassSelectionCommonView>();
}
public void SelectClass() // "Start" Button pressed
{
Toggle selectedToggle = view.GetActiveToggle(); // Get the active Toggle
// ... ?
}
}
So when I call the Method SelectClass() I do not know how to move on. How could I say that this selectedToggle is class xy?
Thanks a lot!
If there is only script selection issue(Not charachter mesh selection) Then, you should attache both script on the object and enable disable them on UItoggle.

JS like enumaration in C#

In JavaScript I can have an array of different objects in each cell, and when enumerating it each cell will get treated as the object it is and not as an underlying common object of the collection.
Lets say I have 2 objects:
class car
{
public color;
...
}
class paint
{
public color;
...
}
Is there a syntax for an enumaration like
car beemer;
paint panda;
...
foreach (thing in [beemer, panda])
{
thing.color = "red";
}
in c#?
Well, you can use dynamic typing if you really want:
public class Paint
{
public string Color { get; set; }
}
public class Car
{
public string Color { get; set; }
}
...
var objects = new object[]
{
new Car { Color = "Red" },
new Panda { Color = "Black" }
};
foreach (dynamic value in objects)
{
Console.WriteLine(value.Color);
}
But it would be more conventional to declare an interface with the property you want, and then make all the relevant types implement the interface:
public interface IColored
{
string Color { get; set; }
}
public class Paint : IColored
{
public string Color { get; set; }
}
public class Car : IColored
{
public string Color { get; set; }
}
...
var objects = new IColored[]
{
new Car { Color = "Red" },
new Panda { Color = "Black" }
};
foreach (IColored value in objects)
{
Console.WriteLine(value.Color);
}
This is:
More efficient
Safer, as then you know at compile-time that every value you're iterating over has a Color property.
If you implement an interface with the color property defined on the interface will be able to achieve this.
public interface IHasColor
{
string color { get; set; }
}
public class car : IHasColor
{
public color { get; set; }
...
}
foreach (IHasColor thing in new IHasColor[] { beemer, panda })
{
thing.color = "red";
}

NullReferenceException and I Don't Know Why

I have two classes:
class Player
{
public string Id { set; get; }
public int yPos { set; get; }
public List<Shot> shots;
public Player(string _Id, int _yPos)
{
Id = _Id;
yPos = _yPos;
}
}
class Shot
{
public int yPos { set; get; }
public Shot(int _yPos)
{
yPos = _yPos;
}
}
When I try to put new Shot in list of shots for the player I get NullReferenceException:
Player pl = new Player("Nick",50);
pl.shots.Add(new Shot(pl.yPos)); // this line throws exception
Probably something ultimately simple.
In your Player constructor, just initialize shots = new List<Shot>();
You need to new the shots in the Player constructor (or before you add to it).
shots = new List<Shot>();
I like the below a bit better, only initialize shots if you need it and if you ever need to add logic to accessing Shots, you can without having to alter the use of Shots all over the place.
private List<Shot> _shots;
public List<Shot> Shots
{
get
{
if (_shots == null)
{
_shots = new List<Shot>();
}
return _shots;
}
set
{
_shots = value;
}
}

Categories

Resources