How to make a static class Derive by MonoBehaviour - c#

recently I am making a game. There is a script named SizePositionForBullet.cs
the code of it was as:-
using UnityEngine;
using UnityEngine.UI;
public class SizePositionForBullet : MonoBehaviour
{
#region variables
//public variables
public Slider widthSetByUser;
public Slider heightSetByUser;
public Slider posXSetByUser;
public Slider posYSetByUser;
//private variables
public float width;
public float height;
public float posX;
public float posY;
#endregion
void Update()
{
#region Getting Player Prefs
posX = PlayerPrefs.GetFloat("posX", 323);
posY = PlayerPrefs.GetFloat("posY", 175);
width = PlayerPrefs.GetFloat("Width", 150);
height = PlayerPrefs.GetFloat("Height", 150);
#endregion
}
public void GetSliderValue(int pos)
{
if (pos == 1)
{
PlayerPrefs.SetFloat("posX", posXSetByUser.value);
}
if (pos == 2)
{
PlayerPrefs.SetFloat("posY", posYSetByUser.value);
}
if (pos == 3)
{
PlayerPrefs.SetFloat("Width", widthSetByUser.value);
}
if (pos == 4)
{
PlayerPrefs.SetFloat("Height", heightSetByUser.value);
}
}
}
So I need to use it's height , width and posX, posY variable in other class. So I added this code in class
public SizePositionForBullet _instance;
public static SizePositionForBullet Instance
{
get{
if(_instance == null)
{
_instance = GameObject.FindObjectOfType<BulletSizePosition>();
}
return _instance;
}
}
But when I use it in other class as it:-
float width = BulletSizePosition.Instance.width;
Unity saying: Null refrence Exception Object refrence not set to an instance of object at Assets/Scripts/BulletScript
How to solve it?

Your private _instance must be static too.
You are using the Singleton pattern. If this class reflect only player save (playerprefs) you don't have to make inheriting from MonoBehaviour.
public class MyPlayerSettings
{
public float Size;
...
private MyPlayerSettings()
{
LoadPreferences();
}
public void LoadPreferences()
{
// Get all your pref here
Size = PlayerPrefs.GetFloat("Size");
...
}
public static MyPlayerSettings Instance
{
get
{
if(instance == null)
{
instance = new MyPlayerSettings();
}
return instance;
}
}
private static MyPlayerSettings instance;
}

Related

Having trouble passing data through Lists

What i wanted to do
I have a class (BlackBoard) that holdes data. and class NPC Gets the data from (BlackBoard). (NPC_Guard) inherits from (NPC) which uses (NPC_Movement) to move by using the data from (BlackBoard).
BlackBoard class
public sealed class BlackBoard : MonoBehaviour
{
#region Singleton
private static BlackBoard instance = null;
public static BlackBoard Instance
{
get
{
if (instance == null)
{
instance = new BlackBoard();
}
return instance;
}
}
#endregion
[SerializeField] List<Transform> NavigationPoints = new List<Transform>();
public List<Transform> Get_NavigationPoints() => NavigationPoints;
public void Set_NavigationPoints(List<Transform> T) => NavigationPoints = T;
}
NPC_Movement class
public class NPC_Movement
{
Vector3 direction;
List<Transform> _navigationPoints = null;
[SerializeField] public List<Transform> NavigationPoints;
{
get
{
if (_navigationPoints == null)
{
_navigationPoints = BlackBoard.Get_NavigationPoints();
}
return _navigationPoints;
}
}
BlackBoard BlackBoard = BlackBoard.Instance;
public void Move()
{
// A complex movement function which uses NavigationPoints
}
}
NPC class
public abstract class NPC : MonoBehaviour
{
[SerializeField] protected NPC_Movement Movement;
}
NPC_Guard class
public class NPC_Guard : NPC
{
void Update()
{
Movement.Move();
}
}
Problem
NPC_Movement class does not get the NavigationPoints List .
What am i doing wrong
please help

C# Game Engine - Adding an Instance of a Transform Class to a List of Components in the Game-Object Class & being able to access its methods

I am building a C# Game Engine for a College Project and I am facing some problems, I have a class called GameObject that contains a List of Component (Which is another Class), I created a class that saves a Vector3 Struct called Transform which Inherits from the Component class.
Now when I try to add the New Instance of Transform into the Component List in Gameobject it doesn't allow me to access the internal methods of the Transform class or do something like get the X coordinate:
// This is the List inside the class GameObject
public List<Component> Components = new List<Component>();
// This is the new Instance of Transform
Transform transform = new Transform();
// This is how I tried to add the new object to the list above
AddComponent(transform);
public void AddComponent(object component)
{
Components.Add((Component)component);
}
// This Works
Console.WriteLine(transform.Position.X);
// However, this line bellow does not allow me to use 'Position'
Console.WriteLine(Components[0]);
The Full Code is Listed Bellow for a Clearer Picture
GameObject Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BoBo3D_George.R_Dor.S
{
public class GameObject
{
// GameObject Class Fields
public List<Component> Components = new List<Component>();
private bool _isEnabled = true;
private string _name;
// ------------------------------
// GameObject Class Constructor
public GameObject(string name)
{
_name = name;
Transform transform = new Transform();
AddComponent(transform);
Rigidbody rigidBody = new Rigidbody();
AddComponent(rigidBody);
Console.WriteLine(transform.Position.X);
Console.WriteLine(Components[0]);
Console.WriteLine(Components[1]);
}
// ------------------------------
// GameObject Class Properties
public string Name
{
get
{
return "Object Name: " + _name;
}
set
{
_name = value;
}
}
public bool IsEnabled
{
get
{
return _isEnabled;
}
}
// ------------------------------
// GameObject Class Methods
public void Disable()
{
throw new System.NotImplementedException();
}
public void Enable()
{
throw new System.NotImplementedException();
}
public void Destroy()
{
throw new System.NotImplementedException();
}
public void AddComponent(object component)
{
Components.Add((Component)component);
}
public void RemoveComponent(object component)
{
throw new System.NotImplementedException();
}
public object GetComponent(int compNum)
{
throw new System.NotImplementedException();
}
}
}
Component, Transform & RigidBody Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BoBo3D_George.R_Dor.S
{
public abstract class Component : IComponent
{
// IComponent Interface Implementation in Component Class
public void OnDisable()
{
throw new NotImplementedException();
}
public void OnEnable()
{
throw new NotImplementedException();
}
public void Start()
{
throw new NotImplementedException();
}
public void Update(float deltaTime)
{
throw new NotImplementedException();
}
}
// Transform Class Componnent
class Transform : Component
{
public Vector3 Position = new Vector3() { X = 0, Y = 0, Z = 0 };
public override string ToString()
{
string info;
info = Position.ToString();
return info;
}
}
// Rigidbody Class Componnent
class Rigidbody : Component
{
private bool _useGravity = false;
private float _g = Physics.Gravity();
private float _timeScale = 0;
private float _fallVelocity = 0;
private float _gravityScale = 0;
private string _info;
public bool UsingGravity
{
get
{
return _useGravity;
}
}
public override string ToString()
{
return $"Gravity:({_useGravity})\n" + _info;
}
public bool ToggleGravity()
{
if (_useGravity == true)
{
_useGravity = false;
}
else
{
_useGravity = true;
}
return _useGravity;
}
public float ActiveGravity()
{
if (_useGravity == true)
{
_timeScale++;
_fallVelocity = _g * _timeScale;
_gravityScale = (_g/2) * (_timeScale * _timeScale);
}
else
{
_timeScale = 0;
_fallVelocity = 0;
_gravityScale = 0;
}
_info = "Time:" + _timeScale + "\nVelocity:" + _fallVelocity + "\nHeight:" + _gravityScale;
return _gravityScale;
}
public void ApplyConstantForce(float incrementation, Vector3 directionInV3)
{
}
}
}

Design Pattern - Decorator. Is correct used in my program?

I have a quesition.
Is in this example did i asue correctly design pattern - decorator?
I want to increase speed of plane after decorate.
Does decorator always has to add new methods? Can only overwrite existing methods?
This is IPlane interface:
interface IPlane
{
void MoveLeft();
void MoveRight();
Rectangle GetPlaneBody();
int GetHealthPoints();
int GetSpeed();
Bullet Shot();
void SetSpeed(int speed);
}
This is plane class:
public class Plane : IPlane
{
private Rectangle PlaneBody = new Rectangle();
private int HealthPoint;
private int x=200;
private int speed;
private Bullet Amunition = new Bullet();
private static Plane instance;
private Plane() { }
public static Plane Instance
{
get
{
if (instance == null)
{
instance = new Plane();
instance.PlaneBody.Height = 125;
instance.PlaneBody.Width = 115;
instance.PlaneBody.X = 200;
instance.PlaneBody.Y =600;
instance.HealthPoint = 1000;
instance.speed = 10;
}
return instance;
}
}
public void MoveLeft()
{
if(x>-10)
x -= speed;
PlaneBody.X = x;
}
public void MoveRight()
{
if(x<1165)
x += speed;
PlaneBody.X = x;
}
public Rectangle GetPlaneBody()
{
return PlaneBody;
}
public int GetHealthPoints()
{
return HealthPoint;
}
public int GetSpeed()
{
return speed;
}
public Bullet Shot()
{
Bullet bullet = new Bullet();
bullet.SetDamage(Amunition.GetDamage());
bullet.SetSpeed(Amunition.GetSpeed());
bullet.SetCoordinates(x+10, this.PlaneBody.Y - 30);
return bullet;
}
public void SetSpeed( int speed)
{
this.speed = speed;
}
}
This is abstract decorator:
class AbstractPlaneDecorator : IPlane
{
protected IPlane plane;
public AbstractPlaneDecorator(IPlane plane)
{
this.plane = plane;
}
public int GetHealthPoints()
{
return plane.GetHealthPoints();
}
public Rectangle GetPlaneBody()
{
return plane.GetPlaneBody();
}
public int GetSpeed()
{
return plane.GetSpeed();
}
public virtual void MoveLeft()
{
plane.MoveLeft();
}
public virtual void MoveRight()
{
plane.MoveRight();
}
public void SetSpeed(int speed)
{
plane.SetSpeed(speed);
}
public Bullet Shot()
{
return plane.Shot();
}
}
And concrete decorator:
class IncreaseSpeedDecorator : AbstractPlaneDecorator
{
public IncreaseSpeedDecorator(IPlane plane) : base(plane)
{
}
public override void MoveLeft()
{
plane.MoveLeft(); // move two times faster
plane.MoveLeft();
}
public override void MoveRight()
{
plane.MoveRight(); // move two times faster
plane.MoveRight();
}
}
This decorator makes that plane moves 2 times faster (He performs the same method twice). Does it meet the rules of decorator pattern?
I would say the implementation is fine.
I don't know the exact context of your code, but it might be a bit strange that if you ask your decorator for the plane's speed, it will return the plane's base speed, but the plane is moving twice as fast. I think a better name for the decorator to describe its funcionality would be DoubleMoveDecorator or something like that, since it doesn't actually do anything with the plane's speed.

Unity C# how to change bool in function

I am currently writing an application in C# with Unity, and I've hit a small stumbling block. I'm trying to change the value of a bool in the buyBusinessCourse() method of a class, but the value is unaffected. The initial value of the boolean is set to false, then I want the update method to run an if statement if it returns true.
public Text healthText;
public Text hungerText;
public Text moneyText;
public Text ageText;
public GameObject youDied;
public GameObject notEnoughMoney;
public GameObject mainScreenPanel;
public GameObject healthPanel;
public GameObject hungerPanel;
public GameObject storePanel;
public GameObject moneyPanel;
public GameObject bicycleImage;
public GameObject businessButton;
public GameObject boughtBusiness;
public int health;
public int hunger;
public int money;
public int age;
private bool business;
public void buyBusinessCourse()
{
if (money >= 3000)
{
money -= 3000;
moneyText.text = "Money: " + money;
Debug.Log("1");
businessButton.SetActive(false);
boughtBusiness.SetActive(true);
bool business = true;
Debug.Log(business);
return;
}
else
{
StartCoroutine(notEnoughMoneyCaroutine());
Debug.Log("2");
}
}
private void Start()
{
bool business = false;
Debug.Log(business);
}
//Update
private void Update()
{
if (health<0 | hunger<0 )
{
youDied.SetActive(true);
mainScreenPanel.SetActive(false);
healthPanel.SetActive(false);
hungerPanel.SetActive(false);
storePanel.SetActive(false);
moneyPanel.SetActive(false);
}
if (business == true)
{
Debug.Log("update"+business);
}
}
}
You don't need to respecify the type, just do business = true. However you are creating a local variable.
You've redefined business in if statement.
public void buyBusinessCourse()
{
if (money >= 3000)
{
...
bool business = true;
...
If you want to change the value of the business bool you need to write this.business=true or business=true.
public void buyBusinessCourse()
{
if (money >= 3000)
{
...
this.business = true;
...
Example
class Rect {
private int width;
private int height;
Rect(int width, int height) {
this.width=width; //Change the value of 'width member of Rect class'
this.height=height; //Change the value of height to given parameter.
}
changeWidthToTen() {
this.width=10;
}
}

The member XXX cannot be used as a method or delegate

I have done copied this of a tutorial online, but when I compile it shows 2 errors as below:
Non-invocable member 'Feature.choices' cannot be used like a method
and
The member `Feature.choices' cannot be used as method or delegate
The last "choices" in the script has a red squiggly line. Any idea that might be wrong?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class FeatureManager : MonoBehaviour {
public List<Feature> features;
public int currFeature;
void OnEnable()
{
LoadFeatures();
}
void OnDisable()
{
SaveFeatures();
}
void LoadFeatures()
{
features = new List<Feature>();
features.Add(new Feature(("hair"), transform.FindChild("hair").GetComponent<SpriteRenderer>()));
}
void SaveFeatures()
{
}
}
[System.Serializable]
public class Feature
{
public string ID;
public int currIndex;
public Sprite[] choices;
public SpriteRenderer renderer;
public Feature(string id, SpriteRenderer rend)
{
ID = id;
renderer = rend;
UpdateFeature();
}
public void UpdateFeature()
{
choices = Resources.LoadAll<Sprite>("Character/" + ID);
if (choices == null || renderer == null)
return;
if (currIndex < 0)
currIndex = choices.Length - 1;
if (currIndex >= choices.Length)
currIndex = 0;
renderer.sprite = choices(currIndex);
}
}
Change this
renderer.sprite = choices(currIndex);
to this:
renderer.sprite = choices[currIndex]; // use square brackets not parenthesis

Categories