Basically I have 3 classes: Game, Level and Player (which is a GameObject). Stripped to the bare minimum it looks something like this:
class Game
{
private Level[] levels;
private Player player;
public Game()
{
levels = new []{new Level(player)};
player = new Player(levels[0]);
}
}
class Level
{
private List<GameObject> gameObjects;
public Level(Player player)
{
gameObjects.Add(player);
}
public void DoSomething() {}
}
class Player : GameObject
{
private Level level;
public Player(Level level)
{
this.level = level;
level.DoSomething();
}
}
abstract class GameObject {}
Is it possible to make this work somehow? player must be created inside Game.
Fix your design. There is no "has-a" relation between player and level, in neither direction (or at least not in both). Or if you think there is, explain why tou think so.
As you found out, using your current design you can't instantiate the one without the other, creating a circular dependency. Of course, to "just make it work" you can create a property or setter method:
pubic class Player
{
private Level _level;
public Level Level
{
get { return _level; }
set { _level = value; }
}
// Or auto-implemented property
public Level Level { get; set; }
public Player()
{
}
}
(Or the same, but then for the Level).
Now you can instantiate a player without requiring a level:
var player = new Player();
var level = new Level(player);
player.Level = level;
As stated before, you can't instantiate one object without already having the other. If you want to keep the design you have now a solution would be to have a Game reference in each other class, like this:
class Level
{
private Game game;
public Level(Game game)
{
this.game = game;
}
}
class Player
{
private Game game;
public Player(Game game)
{
this.game = game;
}
}
You would construct them inside the Game class like this:
levels = { new Level(this) } // (this refers to the instance of Game)
player = new Player(this);
since the constructors accept an instance of Game
Then to access the levels or player object, you would do this inside Level or Player:
this.game.levels
or
this.game.player
Well, next time add Unity tag to your question.
As it is now it is not going to work because currently Player class requires instance of Level class (in constructor) and Level class requires instance of Player class - this makes circular dependence and neither object can be instantiated. So first of all we should break it by removing Player to Level aggregation. Because of condition that we have (Player must be instantiated only inside Game class) we should mark it as abstract :
abstract class AbstractPlayer : GameObject
{
public Level level { get; set; }
}
Now we can modify Game class with new logic and add nested concrete Player class that inherits from AbstractPlayer :
class Game
{
private List<Level> levels;
private Player player;
public Game()
{
player = new Player();
Levels.Add(player);
}
// uncomment this method if you need it
//public Player CreatePlayer()
//{
// return new Player();
//}
private class Player : AbstractPlayer
{
public Player()
{
}
}
}
class Level
{
private List<GameObject> gameObjects;
public Level(Player player)
{
gameObjects.Add(player);
player.Level = this;
}
public void DoSomething() {}
}
Related
I'm working on a weapon system that for my fps game. The player class contains it's own methods that might need to change when a weapon is used. The problem is I want to define the methods that will be replaced with player class' methods on the weapon class.
For example I have a shooting coroutine which uses private members of Player class, I want to change the corouitine using delegates but a coroutine defined in the Weapon class won't be able to access those members.
I know that I can define the coroutine that will come with given Weapon at the Player class and change it according to the attached item, but for clarity of the code, I want to define the shooting corouitines on the Weapon classes. Is there any approach to overcome this issue? Thanks in advance.
If I understand you correctly, something like this should work?
public interface IWeapon
{
void Shoot();
}
// -------------------------------------
public class WaterGun : IWeapon
{
void Shoot()
{
// Shoot water?
}
}
// -------------------------------------
public class LaserPistol : IWeapon
{
void Shoot()
{
// Shoot laser?
}
}
// -------------------------------------
public class Player {
IWeapon weapon;
void Start()
{
this.weapon = new WaterGun();
// later
this.weapon = new LaserPistol();
}
IEnumerator Shoot()
{
// player shoot logic here then weapon-specific logic ->
this.weapon.Shoot();
}
}
But if you simply want to keep a function in a variable, there are ways to do that too, for example:
Action shootFunction;
var waterGun = new WaterGun();
shootFunction = waterGun.Shoot; // assigning a reference to the function without executing the method
shootFunction(); // calls waterGun's Shoot() method
I think you need to detail what you have & what you want to achieve in order to get a good answer here.
It looks like your question boils down to:
I want to define the shooting corouitines(sic) on the Weapon classes
Yeah, we can do that. Let's start by looking at the bits we'd need. In this scenario, it makes sense that we use an interface:
public interface IWeapon
{
bool weaponFiring {get;}
IEnumerator StartWeaponFire ( Player player );
}
Let's look at a sample weapon:
public class WaterPistol : IWeapon
{
public bool weaponFiring { get; private set; }
public IEnumerator StartWeaponFire ( Player player )
{
weaponFiring = true;
Debug.Log ( "Squirt!" );
// Do your weapon logic/animation/cooldown here ..
yield return new WaitForSeconds ( 0.5f );
// We can acccess the 'player' data because we've sent a reference as an argument.
player.currentHealth -= 1;
Debug.Log ( "..." );
weaponFiring = false;
}
}
Now, to run the StartWeaponFire is just as easy as if the coroutine were actually on the player, but it's on the IWeapon instead.
public class Player : MonoBehaviour
{
// An example of data on this player class.
public float currentHealth { get; set; }
// A reference to the current weapon. Has the coroutine we want to start.
public IWeapon currentWeapon { get; set; }
// This can be used to manually stop a coroutine if needed.
private Coroutine _weaponCoroutine;
private void Update ( )
{
if ( Input.GetMouseButton ( 0 )
&& currentWeapon != null
&& !currentWeapon.weaponFiring )
{
_weaponCoroutine = StartCoroutine ( currentWeapon.StartWeaponFire ( this ) );
}
}
}
Notice we're starting a coroutine which has been defined on the currentWeapon, and we're sending through a reference to the Player class. The other method, the 'coroutine' in this case, can then call the public fields, properties and methods of the Player instance.
This is great way to enable an item to define a "coroutine" but allow a specified object to run that coroutine code. This scenario would allow you to have multiple 'players' be able to run the same coroutine, and you don't need to clutter your `Player' class with code for each individual weapon you might include in the game.
I've been trying to perfectly structure this project I'm working on in different classes while maximizing the benefits of inheritance. So far however, it's given me more headaches than benefits.
Consider this:
public class SuperClass : MonoBehaviour
{
[SerializeField] protected Camera _camera;
}
and this
public class SubClass : SuperClass
{
}
Both scripts are attached to different game objects in the scene.
The Camera is to be assigned by dragging it in the inspector
I tried this, and unity seemed to tell me that I had to assign the camera to the SuperClass game object AND to the subclass game object, which makes no sense to me.
How can I assign a camera to SuperClass.cs, which is then used and shared by all of its subclasses?
Thanks in advance!
shared by all of its subclasses
Shared by classes could can only be achieved by using "static" (static variable or singleton).
A workaround could be
public class SubClass :SuperClass
{
[SerializeField] Camera camera;
void Awake()
{
if(camera!=null)
{
_camera=camera;
}
}
// Start is called before the first frame update
void Start()
{
camera=_camera;
}
}
To further extend the solution, you could write a editor script or just get the camera from the code.
You need to create public static Camera property somewhere and reference it in your code, using property:
public static class StaticValues
{
public static Camera Camera {get; set;}
}
public class SuperClass : MonoBehaviour
{
[SerializeField] protected Camera _camera
{
get
{
return StaticValues.Camera;
}
set
{
StaticValues.Camera = value;
}
}
}
public class SubClass : SuperClass
{
}
First I want to give some context. I got two different classes (class Player and class Enemy), each class contains different data, but they both hold the value "int Initiative".
public class Enemy : MonoBehaviour
{
public int initiative;
//More code
}
public class Player : MonoBehaviour
{
public int initiative;
//More code
}
On my project I have several units from both classes and they are stored on 2 different lists of objects
private List<Player> players;
private List<Enemy> enemies;
void Awake()
{
players = new List<Player>();
enemies = new List<Enemy>();
}
Is not shown in the code, but each unit is being sent and storaged on those list depending on their class.
Now my question:
Is there any way of combining both list into a single list keeping all the different objects? (I tried to do this, but didn't get far)
If there is no way of combining both lists because they contain different types of objects, could I create a single list that only storage the int initiative, type of object as well as the position on their previous list? (so I can refer to the lists (players and enemies) when needed. Please explain me how I could achieve this (if possible with some code).
With this I am trying to create some sort of system that will look at the initiative of each unit and call them in order starting for the one that has the highest.
Please I am pretty new in C# and coding in general, so excuse me if the question is too simple, or doesn't make sense.
Thanks in advance :)
You can do something like this:
public class MonoBehaviour
{
public int initiative;//Since you are using inheritance this can be set here
}
public class Enemy : MonoBehaviour
{
//More code
}
public class Player : MonoBehaviour
{
//More code
}
Here is the code to merge them into one list:
List<MonoBehaviour> list = new List<MonoBehaviour>()
list.Add(new Enemy());
list.Add(new Player());
When you want to process them differently somewhere for example you create a method as below:
void ProcessList(List<MonoBehaviour> list)
{
foreach(var l in list)
{
if(l is Enemy)
{
var enemy = (Enemy) l;
//process the enemy
}
else
{
var player = (Player) l;
//process as a player
}
}
}
You can use inheritance. Having base for both Enemy and Player.
public class AliveEntity
{
public string Name {get;set;}
public double HP {get;set;}
}
public class Player : AliveEntity
{ /*...*/ }
public class Enemy : AliveEntity
{ /*...*/ }
And then the list could be List<AliveEntity>.
I'm making a game in Unity3D with C# for mobile devices and can't figure out how to check which scene was loaded before the current scene. I need to check this to change the spawn point from the player gameobject. First I added a simple script to my buttons (loadnextscene and loadprevscene)
public class SwitchScene : MonoBehaviour {
public int sceneNumber;
public void LoadScene(int sceneNumber) {
Application.LoadLevel(sceneNumber);
}
}
A second scripts handles the touch input from the user and changes the movement of the player object.
So, for example: If the player clicks on the "load previous scene" button in the second Level to switch to the first level again, I want to set the spawn point of the player object on the right half on the screen and not on the left side like when the game was started the first time.
I tried it with Singleton and PlayerPrefs, but it did not work out.
You need to save the scene number to some variable before LoadScene, then check it after the scene loaded.
The only problem is that this variable will be destroyed after the new scene is loaded. So, to prevent it, you can use DontDestroyOnLoad. Here is what you do:
First, create a new empty game object, and attach the following script to it:
using UnityEngine;
using System.Collections;
public class Indestructable : MonoBehaviour {
public static Indestructable instance = null;
// For sake of example, assume -1 indicates first scene
public int prevScene = -1;
void Awake() {
// If we don't have an instance set - set it now
if(!instance )
instance = this;
// Otherwise, its a double, we dont need it - destroy
else {
Destroy(this.gameObject) ;
return;
}
DontDestroyOnLoad(this.gameObject) ;
}
}
And now, before you load, save the scene number in the Indestructable object:
public class SwitchScene : MonoBehaviour {
public int sceneNumber;
public void LoadScene(int sceneNumber) {
Indestructable.instance.prevScene = Application.loadedLevel;
Application.LoadLevel(sceneNumber);
}
}
And last, in your scene Start() check Indestructable.instance.prevScene and do your magic accordingly.
More info here:
http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
*I did not compile the code, so there may be some errors, but this is the general idea.
Why did the PlayerPrefs approach did not work?
I think its the easiest way to solve your problem.
public class FirstLevel : MonoBehaviour {
public void Start() {
PlayerPrefs.SetString("SceneNumber", SceneManager.GetActiveScene().name);
}
}
And then in the second scene simply read the saved PlayerPrefs
public class SecondLevel : MonoBehaviour {
string PrevScene;
public void Start() {
PrevScene = PlayerPrefs.GetString("SceneNumber");
// if there will be a third scene, etc.
PlayerPrefs.SetString("SceneNumber", SceneManager.GetActiveScene().name);
}
public void GoToPrevScene() {
SceneManager.LoadScene(PrevScene);
}
}
You can solve this problem with a single static member variable in the SwitchScene class. No need for the singleton pattern or DontDestroyOnLoad.
public class SwitchScene : MonoBehaviour
{
public int sceneNumber;
private static int previousScene;
private int oldPreviousScene;
void Start()
{
oldPreviousScene = previousScene;
previousScene = sceneNumber;
}
public void HandleLoadPrevButtonClick()
{
SceneManager.LoadScene(oldPreviousScene);
}
}
I have a declared entity of a class, and want to assign different pre-made templates to it without the templates ever changing. Using a const doesn't seem to do the trick.
Example:
Weapon w1;
w1 = Sword; // premade weapon.
w1.reducedamage(1); // for example a debuff
In this case the premade weapon's damage would be decreased, and it would no longer be available as a template. This problem becomes more profound with enemies.
Example:
Enemy enemy;
enemy = enemies[r] // r being a randomly generated integer and enemies a list of enemy templates
Fight(player,enemy); // this method would resolve a fight between the two entities of the type Character.
This problem would not be visible in the player class, since player is a single reference being passed along all the game methods - because there is only one player. Every time the player fights, an enemy template would be "corrupted".
How would I create templates or classes/structs in general that always pass by value, meaning that the properties of a first class would have the same values as a second, without any relationship between the two classes?
The only success I've gotten with this is to create a method that manually copies each attribute of every class that has a template onto another entity of the same class; but this is extremely unpractical since it needs constant upgrading whenever a new class is added, or an old one changed.
I must be missing something. This seems like a reasonably simple issue that is easily solved by inheritance, perhaps in conjunction with some sort of Factory. First, you don't want to use a reference to a single instance, you want to create a new instance each time so it is a unique object. I prefer classes over structs, but you could easily create a new struct as well. You could use a Factory to create various pre-configured instances of the objects that have pre-defined values. For example, the Sword of Damocles or the Sword of Destiny.
public static class WeaponFactory
{
public static Weapon CreateSword(SwordType type)
{
var sword = new Sword(); // plain, old default sword
// override properties based on type
switch (type)
{
case SwordType.SwordOfDamocles:
sword.FallTime = GetRandomFutureTime();
break;
case SwordType.SwordOfDestiny:
sword.Invincible = true;
break;
...
}
return sword;
}
...
}
Alternative using Actions
public static class WeaponFactory
{
public static Weapon Create<T>(Action<T> decorator) where T : IWeapon, new()
{
var weapon = new T();
decorator(weapon);
return weapon;
}
public static void SwordOfDamocles(Sword sword)
{
sword.FallTime = GetRandomFallTime();
}
public static void SwordOfDestiny(Sword sword)
{
sword.Invincible = true;
}
}
var weapon = WeaponFactory.Create(WeaponFactory.SwordOfDamocles);
What you want is object cloning. You can implement it via the ICloneable interface[1]. That requires that you implement your own cloning mechanism though--you have to do the heavy lifting.
However, what you probably should do instead is just have the constructor take a parameter that represents the template you want, and then fill the properties of the object in question based on that template. That's the direction I go when I want to make duplicate things with a base set of values.
You could do actual copying (e.g. provide a copy constructor as in http://msdn.microsoft.com/en-us/library/ms173116(v=vs.80).aspx ), but what I've seen most often in such cases is a factory pattern, e.g. Weapon w1 = Weapon.CreateSword(); or Enemy e=Enemy.CreateEnemyOfType(r);
you could build a method to return multiple enemies in either a generic collection or array into your enemy class. Something like:
public shared function getEnemies(num as integer, type as string) as list(of clsEnemy)
dim enemyGroup as list(of clsEnemy)
for i = 0 to num - 1
dim thisEnemy as new clsEnemy(type)
enemyGroup.add(thisEnemy)
next
return enemyGroup
end function
Contrary to copying objects to implement some kind of "applied object" pattern, it's good to keep in mind it's not the sword "base item" that is being altered, but the item your player is carrying.
For example, a given sword, say "rusty old sword", will always have a base damage of 50. Now if someone applies "old stuff gets better magic" to it, it's not the "rusty old sword" that gets more damage: if some other player that hasn't got that kind of magic picks up the item, it's back to its base damage of 50.
So if you implement some kind of EquippedWeapon (or even EquippedItem) class, you can let your player equip weapons and give it extended properties. Something like this to declare a Sword:
interface IWeapon
{
int Damage { get; }
}
class Sword : IWeapon
{
public int Damage { get; private set; }
public Sword()
{
this.Damage = 50;
}
}
Now we have a sword with a base damage of 50. Now to let the player carry this sword:
interface IDamageModifier
{
int Damage { get; set; }
}
class EquippedWeapon : IWeapon
{
public int Damage
{
get
{
return CalculateActualDamage();
}
}
public List<IDamageModifier> DamageModifiers { get; set; }
private IWeapon _baseWeapon = null;
public EquippedWeapon(IWeapon weapon)
{
_baseWeapon = weapon;
}
private int CalulcateActualDamage()
{
int baseDamage = _baseWeapon.Damage;
foreach (var modifier in this.DamageModifiers)
{
baseDamage += modifier.Damage;
}
return baseDamage;
}
}
A weapon contains a list of active modifiers, that affect the damage of the carried item, but not the base item. This way you can share one Sword instance with many (non-)playable characters.
Now if the player gets attacked and that attack has a damage effect, you simply apply that to the item(s) the player is carrying, so each successive attack from that player will have those effects applied:
class Player
{
public EquippedWeapon PrimaryWeapon { get; set; }
public Player()
{
this.PrimaryWeapon = new EquippedWeapon(new Sword());
}
public void UnderAttack(Attack attack)
{
// TODO: implement
if (attack.Buffs...)
{
this.EquippedWeapon.DamageModifiers.Add(attack.Buffs);
}
}
}
I wrote an answer answering your question directly. But now I see that all you want is to create items that are the same but not linked.
That's what happens anyway when you create an instance. You don’t have to do anything.
If you have:
class Class1
{
public int i;
}
Then:
Class1 c1 = new Class1() { i = 1 };
Class1 c2 = new Class1() { i = 2 };
Text = c1.i.ToString();
Prints "1", not "2".
And if you mean you want a "Player" class with sub-classes "Friend" and "Foe" - That's what inheritance is for:
class Player
{
}
class Friend : Player
{
}
class Foe : Player
{
}
EDIT:
Perhaps this will make the task easier: (The "Duplicate" method)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Class1 c1 = new Class1() { i = 1, j = 2 };
Class1 c2 = Duplicate(c1);
c1.i = 3;
Text = c2.i.ToString();//Prints "1";
}
public Class1 Duplicate(Class1 c)//Duplicates all public properties.
{
Class1 result = new Class1();
PropertyInfo[] infos = typeof(Class1).GetProperties();
foreach (PropertyInfo info in infos)
info.SetValue(result, info.GetValue(c, null), null);
return result;
}
}
public class Class1
{
public int i { get; set; }
public int j { get; set; }
}