• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
fafase

Generic method with objects

6 posts in this topic

Hey,

Being not totally advanced yet with C# I am trying to develop a function that would instantiate a list of object.

[source lang="java"]public static List<T> CreateObjLeft<T>(T type) {
List<T> temp = new List<T>();
for (int i = 0; i < 10; i++) {
temp.Add(type); }
return temp;
}[/source]
This is somehow working, I get my 10 objects but I need to access each instance. I created a default constructor for the object, but at the moment all objects in the list have the same attributes and I need to access the position (it is for a game) so that they do not all show on top of each other.

I am trying to create a pattern of object (circle, triangle...) and I would like to be able to use the same generic function for whatever object I want to create (pretty mush the principle of generic methods...).

I have also tried to cast the object inside as such:

[source lang="csharp"]if (type is Asteroid) {
((Asteroid)type).position = new Vector2(0,0);
}[/source]

But then I get an error Cannot convert type T to my own class. Or trying to access the object of the list in the same fashion:


[source lang="csharp"]if (temp is Asteroid) {
((Asteroid)temp)[0].position = new Vector2(0,0);
}[/source]
Error 5 Cannot convert type 'System.Collections.Generic.List<T>' to 'Tutorial.Asteroid'

Does anyone has a solution in mind? Or I thought of trying to add my custom object type to Generic.List<T> but could not really get it...

Thanks
0

Share this post


Link to post
Share on other sites
Thanks a hell of a bunch!!! Unfortunately I can only upvote once...

Well, that did the trick now I need to review all that and understand how and why it works. I have never heard of Action and delegates (still discovering C#).

Also,I was scared you led me somewhere lost as all my object were on the same spot at first but then I realized you just assign the same position in initCircle (I guess you forgot to use i).

Again thanks for that.
0

Share this post


Link to post
Share on other sites
[quote name='fafase' timestamp='1346140699' post='4974014']
Thanks a hell of a bunch!!! Unfortunately I can only upvote once...

Well, that did the trick now I need to review all that and understand how and why it works. I have never heard of Action and delegates (still discovering C#).

Also,I was scared you led me somewhere lost as all my object were on the same spot at first but then I realized you just assign the same position in initCircle (I guess you forgot to use i).

Again thanks for that.
[/quote]

I'm glad I could help [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
I used the i in initCircle to calculate a, but you probably have to scale up the vector in order to see the circle.
[CODE]
obj.position = new Vector2(x, y) * 100;
[/CODE]
should produce a circle with radius 100. Edited by lwm
2

Share this post


Link to post
Share on other sites
One last thing,

[source lang="csharp"]Action<Asteroid, int, int> initCircle = (obj, i, amount) => {
float a = ((float)i / (float)amount) * MathHelper.TwoPi;
float x = (float)Math.Sin(a);
float y = (float)Math.Cos(a);
obj.position = new Vector2(x, y);
};
[/source]
Action<Asteroid, int, int> this declaration will not work if I pass another object type to it, I tried replacing Asteroid with T but no go. The idea would be that if I pass an object of type SpaceShip, it would create s circle of them. Do I need to create a second Action with the SpaceShip or could I alter the existing one so that anything passed would do.

So I can call
[source lang="csharp"]asteroids.AddRange(PatternAst.CreateMultipleObjects<Asteroid>(10, PatternAst.initCircle));
asteroids.AddRange(PatternAst.CreateMultipleObjects<SpaceShip>(10, PatternAst.initCircle));[/source]
(Obvisouly not at the same time) adn I would get a circle of asteroid and a circle of spaceship.

I would guess there is a way to do so.

Sorry for so many questions.
0

Share this post


Link to post
Share on other sites
The most straight-forward thing would probably be to make all classes that you want to initialize that way implement a common interface, like "IHasPosition".
Or, if you want to make the your PatternAst class even more generic, you can provide a setter action to the method.

[CODE]
public interface IHasPosition
{
Vector2 Position { get; set; }
}
public class Asteroid : IHasPosition
{
public Vector2 Position { get; set; }
}
public class Asteroid2
{
public Vector2 Position { get; set; }
}
public static class PatternAst
{
static void Main(string[] args)
{
// Use the fact, that Asteroid implements IHasPosition
var list1 = CreateCircle<Asteroid>(10, new Vector2(0, 0), 100);
// Asteroid2 does not implement IHasPosition, use second method with setter action
var list2 = CreateCircle<Asteroid2>(10, new Vector2(0, 0), 100, (obj, pos) => { obj.Position = pos; });
}
private static Vector2 PositionInCircle(int i, int amount, Vector2 center, float radius)
{
float a = ((float)i / (float)amount) * MathHelper.TwoPi;
float x = (float)Math.Sin(a);
float y = (float)Math.Cos(a);
return center + new Vector2(x, y) * radius;
}
public static List<T> CreateCircle<T>(int amount, Vector2 center, float radius) where T : class, IHasPosition, new()
{
var list = CreateMultipleObjects<T>(amount);
for (int i = 0; i < list.Count; i++)
{
list[i].Position = PositionInCircle(i, list.Count, center, radius);
}
return list;
}
public static List<T> CreateCircle<T>(int amount, Vector2 center, float radius, Action<T, Vector2> positionSetter) where T : class, new()
{
var list = CreateMultipleObjects<T>(amount);
for (int i = 0; i < list.Count; i++)
{
var pos = PositionInCircle(i, list.Count, center, radius);
positionSetter(list[i], pos);
}
return list;
}
public static List<T> CreateMultipleObjects<T>(int amount) where T : class, new()
{
List<T> temp = new List<T>();
for (int i = 0; i < amount; i++)
{
T obj = new T();
temp.Add(obj);
}
return temp;
}
}
[/CODE] Edited by lwm
2

Share this post


Link to post
Share on other sites
Actually, either I am wrong or this just got me thinking it was it until I figured out it does not do much more than what I was trying to avoid

In the first place I wanted to have a function that could accept different types of object to do the same action.
What I have now is two functions...That is what I wanted to avoid. Then after reading Action is just a function that does not return any value (but is actually slightly slower than a normal function).


There may be a way around this but at the moment this is actually not doing any thing more than what I was trying to avoid. Edited by fafase
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0