Object reference not set to an instance of an object #100 - c#

I know people have asked this before, but it would appear that their solution doesn't work for me or I'm doing something wrong.
public class Sprite
{
private Game m_game;
private SpriteBatch m_spriteBatch;
private string m_filename;
private Texture2D m_texture;
public Sprite(Game game, SpriteBatch spriteBatch, GraphicsDevice graphicsDevice)
{
m_game = game;
m_spriteBatch = spriteBatch;
m_texture = new Texture2D(graphicsDevice, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height);
}
public void LoadSprite(string filename)
{
m_texture = m_game.Content.Load<Texture2D>(filename);
}
}
The error is generated at LoadSprite when I pass "tree" as the filename.
m_texture isn't null because (tried to) initialise it in the constructor.
The same call to Content.Load is used in the main loop fine but I want to move that into the Sprite class.
treeTexture = Content.Load<Texture2D>("tree");
This works fine in the main loop so it shows that the "tree" file exists.
Can anyone see what I'm doing wrong?

m_game or m_game.Content is probably null.

Related

How To Fix SpriteRenderers Not Changing at Runtime

I am trying to change an element of a 2d character at runtime. I've used the code below and it doesn't seem to change the sprite of the character at all. No errors or anyhting but the physical sprite doesn't change. I have used Debug.Log to see if the methods are being called (which they are). I've also included some screenshots of how it is inside of inspector.
Here is what I have so far.
InventoryPanel.cs
public CharacterAppeance ca;
if (item.location == ItemLocation.Boot)//This is set in ItemData.ca
{
ca.SetBoot(item.appaerance[0], item.appaerance[1]);
}
CharacterApperance.cs
public SpriteRenderer leg1ArmorRenderer;
public SpriteRenderer leg2ArmorRenderer;
public SpriteRenderer pelvisArmorRenderer;
public SpriteRenderer shin1ArmorRenderer;
public SpriteRenderer shin2ArmorRenderer;
public void SetBoot(Sprite leg, Sprite shin)
{
leg1ArmorRenderer.sprite = leg;
leg2ArmorRenderer.sprite = leg;
shin1ArmorRenderer.sprite = shin;
shin2ArmorRenderer.sprite = shin;
}
ItemData.cs
public Sprite[] appaerance;
Itemdata in Inspector: http://prntscr.com/nbvgj9
CharacterApperance in Inspector: http://prntscr.com/nbvh7w
InventoryPanel in Inspector: http://prntscr.com/nbvhlr
Thank you all who help :)

Call object on other scene C#

I have this problem that I want to call an object from my first scene then call that object on my second scene . I tried doing this
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
and put it on the object I don't want to destroy then changed my scene on the
void Start(){
SceneManagement.LoadScene("Menu",LoadSceneMode.Single);
}
But it's not there on the heirarchy
Could someone help me out
EDIT:
Now when the next scene is loaded
The object I wanted is not there anymore. It is being destroyed
Create a persistent object
Create a preloader scene here you can place a splash screen or whatever you prefer but the important thing is loading things that should be persistent(maybe such as a network or gamemanager)
Create a script PersistentObject.cs and put the following code in it
private void Awake(){
DontDestroyOnLoad(this.gameObject);
}
Put this script on any object you initialize in the preloader
Access object from anywhere
If you want to access an object in another scene there are several ways but I will assume you do not have any specific reference to the object
So if we have a GameManager.cs and we created a Persistent cube in our preloader called Cube we can get a reference to the gameobject by saying GameObject cube = GameObject.FindGameobjectWithName("Cube");
Now you are able to do whatever you want by using cube
Write less, Do more with singletons
Creating a singleton will also be very useful as well
public static class Singleton<T>: MonoBehavior where T: MonoBehavior{
private static T instance;
//Notice the lower and upper case difference here
public static T Instance{
get{
if(instance == null){
instance = GameObject.FindGameObjectOfType<T>();
}
return instance;
}
}
}
You can then add this to your script make accessing properties easier and reduces the amount of code you have to write
public class Cube: Singleton<Cube>{
private string cubeName = "Jeff";
public void ChangeCubeName(string newName){
cubeName = newName;
}
}
To access this methods of this class you could now call the singleton from anywhere in your code
Example
public class GameManager: MonoBehavior{
private void Start(){
cube.Instance.ChangeCubeName("Joe");
}
}

Viewing area of window?

Hi i need find out size of viewing area of my game window. I found this code :
int height = GraphicsDevice.Viewport.Height;
but return this error:
Object reference not set to an instance of an object.
Can you anyone help me how solve this problem ? Thanks and sorry for my English
I would say that GraphicsDevice.Viewport.Height is null then, not inited yet. GraphicsDevice is inside Microsoft.Xna.Framework.Graphics namespace.
if you are inheriting from game class try with:
this.GraphicsDevice.Viewport.Height
or with
this.Game.GraphicsDevice.Viewport.Height
where are you trying to populate those integers?
added example
using Microsoft.Xna.Framework.Graphics;
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public int screenWidth;
public int screenHeight;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
screenWidth = GraphicsDevice.Viewport.Width;
screenHeight = GraphicsDevice.Viewport.Height;
}
}
Height looks like it could be a class or something due to its capitalization, but the biggest clue is the part in the error where it says object reference. The .Height at the end gets the Height object of Viewport. You need to access a property/member variable of the object (probably named height; the easiest way to find it would be code completion) to assign it to a variable.

Unity2D: UnassignedReferenceException: Variable has not been assigned instantiate

For some reason I get an error which looks like this:
UnassignedReferenceException: The variable LevelComplete of NPad1 has not been assigned.
and this is my code:
public class NPad1 : MonoBehaviour {
public Sprite img1 , img2;
public Rigidbody2D LevelComplete;
void Start () {
gameObject.GetComponent<SpriteRenderer> ().sprite = img1;
}
// Update is called once per frame
void OnTriggerEnter2D(Collider2D other) {
gameObject.GetComponent<SpriteRenderer> ().sprite = img2;
Instantiate (LevelComplete);
}
What have I done wrong?
Referring to this;
Clones the object original and returns the clone.
Which means you will have to instantiate LevelComplete before calling Instantiate(), which returns a clone of the existing object. You probably haven't set the instance in the Unity inspector. For more info, visit this guide on setting public variables.

FlyWeight Pattern: every object parameters became same as updated

Hello everyone ı have a problem with flyweight patter ;
I try to implement flyweight patter to my sprite class. There are tons of smilarty as attributes each Sprite object only diffirences are Position and frame;
Im my code ı have a problem, whenever ı set(Position or frame) of one sprite , every other objects attribute also change, ı dont want that ı want most of attributes are same but frame and position is diffrent for each object.
Here is the code:
public enum Type
{
sprite,
None,
};
public class FactorySprite
{
private LinkList SpriteList = new LinkList();
private Hashtable Sprites = new Hashtable();
public FactorySprite()
{
// SpriteList.AddtoBegining(new Sprite());
Sprites.Add(Type.sprite, new Sprite());
}
public GameSprite getSprite(Type type)
{
// return (Sprite)SpriteList.Search(O);
GameSprite gamesprite = null;
if(Sprites.ContainsKey(type))
{
gamesprite =( GameSprite)Sprites[type];
}
return gamesprite;
}
}
public abstract class GameSprite
{
protected Texture2D texture;
// protected Vector2 position;
protected Texture loadTexture;
// protected int frame;
protected Vector2 Speed;
protected Rectangle SourceRectangle;
protected Color color;
public Type type;
protected SpriteBatch spriteBatch;
public abstract void Draw();
public abstract void Update();
public abstract void setframe(int frame_number);
public abstract void setPosition(int x,int y);
}
public class Sprite : GameSprite
{
private int frame;
private Vector2 position;
public Sprite()
{
frame =0;
type = Type.sprite;
spriteBatch = Game1.GameInstance.spriteBatch;
texture = Texture.Instance().GetTexture();
Speed = new Vector2(0, 1);
color = Color.White;
}
public override void Draw()
{
spriteBatch.Draw(texture,position,Image.Instance().drawframe(this.frame), color);
}
public override void setframe(int frame_number) {this.frame = frame_number; }
public override void setPosition(int x, int y) {this.position = new Vector2(x, y); }
public Type getType()
{
return type;
}
public override void Update(){}
}
Here is manin that ı create factory flayweight and each object that ı create
SpriteManager sm = SpriteManager.Instance();
FactorySprite factory = new FactorySprite();
Sprite s1 = (Sprite)factory.getSprite(Type.sprite);
s1.setframe(6);
s1.setPosition(200, 300);
sm.AddSprite(s1);
Sprite s2 = (Sprite)factory.getSprite(Type.sprite);
s2.setframe(5);
s2.setPosition(100, 100);
sm.AddSprite(s2);
Problem here to be more clear s1 and s2 has same frame and position(whic one is last updated all other object become same)
This thing about the FlyWeight pattern is that every time you ask for one, you get the same instance. Thus every time you call GetSprite you are returning the same one, not a copy but the same one.
So if you call it twice, you now have two references to the same object. If you change it in one place it will change in the other because the two ARE THE SAME THING! That's actually the point of the FlyWeight pattern.
I would suggest that you don't use this pattern where you need different objects as you do.
One way around trhis is to extract all this bits of a Sprite which do not ever change into a new class, which you can then use the FlyWeight pattern on. The changeable bits would stay in the Sprite class, with the addition of a reference to your new 'ImutableSprite' instance.
The Flyweight pattern doesn't apply here.
Flyweight means that you use the same object with a specific in all cases where you want this specific value. Obviously, if you change the value in one place, the change will appear everywhere.
If you want to reduce the number of sprites, you could use immutable semantics: Use a single Sprite instance for a specific set of Position,Frame and create a copy when you want a Sprite with a different set.

Categories

Resources