Jump to content
  • Advertisement
Sign in to follow this  
phil05

C#: Passing objects to other forms?

This topic is 4764 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Say that you made a player object in Form1 : Form, and you open a new window in your application. How can the new window get your object by reference?

Share this post


Link to post
Share on other sites
Advertisement
The easiest way (at least as I remember) is using something called a "controller". A controller, should be a singleton pattern. IE: Something will only have 1 reference in the application.
ie:

class Singleton
{
private static Singleton instance = new Singleton();
private MyObject object = null;
private Singleton()
{
if(instance == null)
{
object = new MyObject();
}
}

public static Singleton Instance
{
get { return instance; }
}

public MyObject GetMyObject
{
get { return object; }
}
}



From your Singleton class, you should be able access each object you create with the singleton. From those objects, you then access the methods of that class.

IE:

public class MyObject
{
private String name;

public MyObject() {}

public String Name
{
set { if(value != null) name = value; }
get { return name; }
}
}



And an example in practice

public class Form1
{
private Singleton instance = Singleton.Instance;
public Form1() {}

MyObject obj = instance.GetMyObject;
obj.Name = "John";
}

public class Form2
{
private Singleton instance = Singleton.Instance;

TextField.Text = instance.GetMyObject.Name;
}



HTH
Rooke

Share this post


Link to post
Share on other sites
The key to this is seperating your user interface (form) from your business logic (rules of the game).

If your forms are just slaves to the game logic, or even better you split it up in to a model-view-controller type paradiagm where the view is completly seperated from the game, this kind of thing just becomes natural.

Try seperating out your concepts (like player, game, enemy, etc) in to seperate class files. Have a form called "GameView" and another called "PlayerView" and see where that kind of thinking leads you.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!