So I'm trying to create this program that works perfect in Visual Studio 2012 at School.
But when I'm at home it's giving me this Thrown Exception error at Public Game1().
Hopefully someone can help me out with this so that way i can actually run my program and finish it.
The Call Stack is:
System.NullReferenceException: Object reference not set to an instance
of an object at Microsoft.Xna.Framework.OpenTKGameWindow.Initialize
() [0x00000] in :0 at
Microsoft.Xna.Framework.OpenTKGameWindow..ctor () [0x00000] in
:0 at
Microsoft.Xna.Framework.OpenTKGamePlatform..ctor
(Microsoft.Xna.Framework.Game game) [0x00000] in :0
at Microsoft.Xna.Framework.GamePlatform.Create
(Microsoft.Xna.Framework.Game game) [0x00000] in :0
at Microsoft.Xna.Framework.Game..ctor () [0x00000] in :0 at MonoGameTest.Game1..ctor () [0x00023] in
/Users/sebnabt/Projects/MonoGameTest/MonoGameTest/Game1.cs:38 at
MonoGameTest.Program.Main () [0x00001] in
/Users/sebnabt/Projects/MonoGameTest/MonoGameTest/Program.cs:19
And my code:
<!-- language: lang-cs -->
region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Input;
endregion
namespace MonoGameTest
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// Maps user keys to display colors
Dictionary<Keys, Color> key_to_color = new Dictionary<Keys, Color>();
// these are the colors guessed by the user, so far.
List<Color>[] player_colors = new List<Color>[10];
// these are the keys that correspond to a dot color
List<Keys> color_letters = new List<Keys>();
Texture2D dot_picture;
KeyboardState old_keyboard_state;
int row;
public Game1() : base()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
base.Initialize ();
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
///
/// // screen constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
protected override void Initialize()
{
row = 0;
// back buffer
graphics.PreferredBackBufferHeight = SCREEN_HEIGHT;
graphics.PreferredBackBufferWidth = SCREEN_WIDTH;
graphics.PreferMultiSampling = false;
graphics.ApplyChanges();
base.Initialize();
// initialize the color dictionary
key_to_color.Add(Keys.R, Color.Red);
key_to_color.Add(Keys.G, Color.Green);
key_to_color.Add(Keys.B, Color.Blue);
key_to_color.Add(Keys.Y, Color.Yellow);
color_letters = new List<Keys>();
foreach (Keys letter in key_to_color.Keys)
{
color_letters.Add(letter);
}
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// load our textures
dot_picture = Content.Load<Texture2D>(#"media\ball");
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// get keyboard state once per frame
KeyboardState keyState = Keyboard.GetState();
// exit the game?
if (keyState.IsKeyDown(Keys.Escape))
{
this.Exit();
}
// erase list of player colors?
else if (keyState.IsKeyDown(Keys.Space))
{
player_colors[this.row].Clear();
}
// player pressed a color key?
else {
foreach (Keys letter in color_letters)
{
if (key_was_released(letter, keyState))
{
add_color(letter);
}
if (this.player_colors [row].Count () >= 4) {
this.row = this.row + 1;
}
}
}
old_keyboard_state = keyState;
base.Update(gameTime);
}
protected override void UnloadContent() {
}
bool key_was_released(Keys key, KeyboardState new_state)
{
return old_keyboard_state.IsKeyDown(key) &&
new_state. IsKeyUp (key);
}
void add_color(Keys key)
{
Color color = key_to_color[key];
if (player_colors[this.row].Count() < 4)
{
player_colors[this.row].Add(color);
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear (Color.CornflowerBlue);
// draw typical sprites
spriteBatch.Begin ();
draw_player_colors (spriteBatch);
spriteBatch.End ();
base.Draw (gameTime);
}
protected void draw_player_colors(SpriteBatch batch)
{
for (int current_row = 0; current_row < 10; current_row++) {
for (int column = 0; column < player_colors[current_row].Count(); column++) {
int x = 100 + column * 70;
int y = 100 + column * 70;
Vector2 loc = new Vector2 (x, y);
Color c = player_colors[current_row].ElementAt (column);
batch.Draw (dot_picture, loc, c);
}
}
}
}
}
Newest Error:
It looks as though I have gotten it to slightly work however I'm now getting an error in the Basic Template on: logoTexture = Content.Load<Texture2D>("logo");
The error will be below
Microsoft.Xna.Framework.Content.ContentLoadException: Could not load
logo asset as a non- content file! ---> System.Exception: The
directory was not found. ---> System.Exception: Could not find a
part of the path
"/Users/sebnabt/Projects/BSMac/BSMac/bin/Debug/BSMac.app/Contents/Resources/Content/logo.xnb".
at System.IO.FileStream..ctor (System.String path, FileMode mode,
FileAccess access, FileShare share, Int32 bufferSize, Boolean
anonymous, FileOptions options) [0x001c6] in
/private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/FileStream.cs:266
at System.IO.FileStream..ctor (System.String path, FileMode mode,
FileAccess access, FileShare share) [0x00000] in
/private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/FileStream.cs:132
at at (wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor
(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
at System.IO.File.OpenRead (System.String path) [0x00000] in
/private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/File.cs:341
at Microsoft.Xna.Framework.TitleContainer.OpenStream (System.String
name) [0x00000] in :0 at
Microsoft.Xna.Framework.Content.ContentManager.OpenStream
(System.String assetName) [0x00000] in :0 --- End
of inner exception stack trace --- at
Microsoft.Xna.Framework.Content.ContentManager.OpenStream
(System.String assetName) [0x00000] in :0 at
Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[Texture2D]
(System.String assetName, System.Action1 recordDisposableObject)
[0x00000] in <filename unknown>:0 --- End of inner exception stack
trace --- at at
Microsoft.Xna.Framework.Content.ContentManager.ReadAsset<Microsoft.Xna.Framework.Graphics.Texture2D>
(string,System.Action1) <0x0076b> at at
Microsoft.Xna.Framework.Content.ContentManager.Load
(string) <0x0020b> at BSMac.Game1.LoadContent () [0x00023] in
/Users/sebnabt/Projects/BSMac/BSMac/Game1.cs:70 at at
Microsoft.Xna.Framework.Game.Initialize () at
BSMac.Game1.Initialize () [0x00002] in
/Users/sebnabt/Projects/BSMac/BSMac/Game1.cs:57 at at
Microsoft.Xna.Framework.Game.DoInitialize ()
at at Microsoft.Xna.Framework.Game.Run
(Microsoft.Xna.Framework.GameRunBehavior) at
at Microsoft.Xna.Framework.Game.Run () at
BSMac.AppDelegate.FinishedLaunching (MonoMac.Foundation.NSObject)
[0x00012] in /Users/sebnabt/Projects/BSMac/BSMac/Main.cs:34 at at
(wrapper dynamic-method) object.[BSMac.AppDelegate.Void
FinishedLaunching(MonoMac.Foundation.NSObject)]
(MonoMac.Foundation.NSObject,MonoMac.ObjCRuntime.Selector,MonoMac.Foundation.NSObject)
at at (wrapper native-to-managed)
object.[BSMac.AppDelegate.Void
FinishedLaunching(MonoMac.Foundation.NSObject)]
(MonoMac.Foundation.NSObject,MonoMac.ObjCRuntime.Selector,MonoMac.Foundation.NSObject)
at at (wrapper managed-to-native)
MonoMac.AppKit.NSApplication.NSApplicationMain (int,string[])
<0x00003> at at MonoMac.AppKit.NSApplication.Main (string[]) at BSMac.Program.Main (string[]) [0x0001d] in
/Users/sebnabt/Projects/BSMac/BSMac/Main.cs:20 at
Are you building in Xamarin Studio? I believe you are experiencing the same problem described in a question from a couple days ago; see my answer there: https://stackoverflow.com/a/18798311/793449
To recap, Xamarin Studio is picking the WindowsGL framework assembly instead of the mac assembly. You should build MonoGame yourself from the latest source (the MonoGame.Framework.MacOS project) and change the reference out in your game.
Related
I am getting the following exception when drawing an image in iOS UI at a very high rate. I have ensure that I am updating the image source from the main thread. We have BLE devices broadcasting signal strength at a 750ms interval and I have ~ 50 around me. So as you could imagine, I am updating that image object often and quickly. It works for a bit, then crashes with this exception.
Here is the exception on crash:
at Xamarin.Forms.BindableObject.SetValueCore (Xamarin.Forms.BindableProperty property, System.Object value, Xamarin.Forms.Internals.SetValueFlags attributes, Xamarin.Forms.BindableObject+SetValuePrivateFlags privateAttributes) [0x00199] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:454
at Xamarin.Forms.BindableObject.SetValue (Xamarin.Forms.BindableProperty property, System.Object value, System.Boolean fromStyle, System.Boolean checkAccess) [0x0004d] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:374
at Xamarin.Forms.BindableObject.SetValue (Xamarin.Forms.BindablePropertyKey propertyKey, System.Object value) [0x0000e] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:356
at Xamarin.Forms.Image.SetIsLoading (System.Boolean isLoading) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\Image.cs:81
at Xamarin.Forms.Platform.iOS.ImageRenderer.TrySetImage (Xamarin.Forms.Image previous) [0x000a4] in D:\a\1\s\Xamarin.Forms.Platform.iOS\Renderers\ImageRenderer.cs:104
at Xamarin.Forms.Platform.iOS.ImageRenderer.OnElementPropertyChanged (System.Object sender, System.ComponentModel.PropertyChangedEventArgs e) [0x00055] in D:\a\1\s\Xamarin.Forms.Platform.iOS\Renderers\ImageRenderer.cs:85
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
at Foundation.NSAsyncSynchronizationContextDispatcher.Apply () [0x00000] in /Users/builder/azdo/_work/1/s/xamarin-macios/src/Foundation/NSAction.cs:178
at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00013] in /Users/builder/azdo/_work/1/s/xamarin-macios/src/UIKit/UIApplication.cs:73
Here is the code that updates the value, its nothing crazy... just an update to the set. I put a breakpoint in the IsMainTread just to make sure its not that, it never hits that.
Looking into the Xamarin Forms code based on the call stack, but best guess is that the BindingContext is becoming null somehow. Is there a way to make this safe or not update if it is?
Any reason I shouldn't be able to update an image at this rate?
private int signalStrength;
public int SignalStrength
{
get
{
return signalStrength;
}
set
{
if (value != signalStrength)
{
if (!MainThread.IsMainThread)
{
Console.WriteLine("not here");
}
signalStrength = value;
if (Data.IsDownload)
{
SignalStrengthImage = "App.Resources.Images.TTSVGIcons.TTsignal_white_" +signalStrength+".png";
}
else
{
SignalStrengthImage = "App.Resources.Images.TTSVGIcons.TTsignal_" + signalStrength + ".png";
}
}
}
}
I am trying to use FFImageLoading like this:
AppDelegate:
CachedImageRenderer.Init();
CachedImageRenderer.InitImageSourceHandler();
var config = new FFImageLoading.Config.Configuration()
{
VerboseLogging = true,
VerbosePerformanceLogging = false,
VerboseMemoryCacheLogging = false,
VerboseLoadingCancelledLogging = false
};
ImageService.Instance.Initialize(config);
var ignore = typeof(FFImageLoading.Svg.Forms.SvgCachedImage);
Preloading:
public void PreloadImages()
{
try
var resources = Assembly.GetExecutingAssembly().GetManifestResourceNames();
foreach (var r in resources)
{
if (!r.EndsWith(".svg")) continue;
try
{
var assemblyName = Application.Current?.GetType()?.GetTypeAssemblyFullName();
ImageService.Instance.LoadEmbeddedResource($"resource://{r}?assembly={Uri.EscapeUriString(assemblyName)}")
//ImageService.Instance.LoadEmbeddedResource($"resource://{r}?assembly={Assembly.GetExecutingAssembly().GetName().Name}")
.Success((info, result) =>
{
Debug.WriteLine($"Preloading success! Key: {info.CacheKey}");
})
.Preload();
}
catch (Exception ex)
{
Debug.WriteLine($"LoaderPage.PreloadImages[{r}]", ex);
}
}
}
When the code runs the images appear on the screens but my Application Output fills up with messages like this:
System.BadImageFormatException: Can't read image size properties. File corrupted?
at FFImageLoading.Decoders.GifDecoder.SourceRegfToDecodedImageAsync (Foundation.NSData nsdata, CoreGraphics.CGSize destSize, System.nfloat destScale, FFImageLoading.Config.Configuration config, FFImageLoading.Work.TaskParameter parameters, FFImageLoading.Decoders.GifDecoder+RCTResizeMode resizeMode, FFImageLoading.Work.ImageInformation imageinformation, System.Boolean allowUpscale) [0x00068] in C:\projects\ffimageloading\source\FFImageLoading.Shared.IosMac\Decoders\GifDecoder.cs:62
at FFImageLoading.Decoders.GifDecoder.DecodeAsync (System.IO.Stream stream, System.String path, FFImageLoading.Work.ImageSource source, FFImageLoading.Work.ImageInformation imageInformation, FFImageLoading.Work.TaskParameter parameters) [0x000e4] in C:\projects\ffimageloading\source\FFImageLoading.Shared.IosMac\Decoders\GifDecoder.cs:45
at FFImageLoading.Work.ImageLoaderTask`3[TDecoderContainer,TImageContainer,TImageView].GenerateImageAsync (System.String path, FFImageLoading.Work.ImageSource source, System.IO.Stream imageData, FFImageLoading.Work.ImageInformation imageInformation, System.Boolean enableTransformations, System.Boolean isPlaceholder) [0x0007c] in C:\projects\ffimageloading\source\FFImageLoading.Common\Work\ImageLoaderTask.cs:337
at FFImageLoading.Work.ImageLoaderTask`3[TDecoderContainer,TImageContainer,TImageView].RunAsync () [0x0047c] in C:\projects\ffimageloading\source\FFImageLoading.Common\Work\ImageLoaderTask.cs:643
2021-02-24 01:50:30.338196+0900 Memorise.iOS[41119:898256] Image loading failed: resource://Memorise.Resources.Cards.pause_Light.svg?assembly=Memorise,%20Version=1.0.0.0,%20Culture=neutral,%20PublicKeyToken=null
System.BadImageFormatException: Can't read image size properties. File corrupted?
Note that some of the SVG are very simple ones and I have no idea why or how they are corrupt and also the do show on the screen.
Has anyone been able to get the preload working. Note that I tried two different ways to do LoadEmbeddedResource but neither worked.
In my xamarin.forms ios application I have 4 ContentPages and 1 Popup(Rg.Plugin)
My Navigation is like this
Page 1--> Page 2 --> Page 3 --> Page 4 --> Popup
I want to navigate to Page 1 from a button click in Popup by removing the pages(2,3,4 and Popup).
I done it like this.
private void OK_Clicked(object sender, EventArgs e)
{
try
{
var countPagesToRemove = 3;
var mainPage = (Application.Current.MainPage as NavigationPage);
for (var i = 1; i < countPagesToRemove; i++)
{
mainPage.Navigation.RemovePage(mainPage.Navigation.NavigationStack[mainPage.Navigation.NavigationStack.Count - 2]);
}
Navigation.PopAsync();
Task.Delay(5);
PopupNavigation.Instance.PopAsync();
}
catch (Exception ex)
{
DisplayAlert("Result", ex.Message, "ok");
}
}
This works perfectly on Android.In ios it throws me this exception.
Foundation.MonoTouchException
Message=Objective-C exception thrown. Name: CALayerInvalidGeometry Reason: CALayer bounds contains NaN: [0 0; 0 nan]
Native stack trace:
Source=Xamarin.iOS
StackTrace:
at ObjCRuntime.Runtime.ThrowNSException (System.IntPtr ns_exception) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.14.1.39/src/Xamarin.iOS/ObjCRuntime/Runtime.cs:406
at ObjCRuntime.Runtime.throw_ns_exception (System.IntPtr exc) [0x00000] in /Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/runtime/Delegates.generated.cs:128
at (wrapper native-to-managed) ObjCRuntime.Runtime.throw_ns_exception(intptr)
at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.14.1.39/src/Xamarin.iOS/UIKit/UIApplication.cs:86
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0000e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.14.1.39/src/Xamarin.iOS/UIKit/UIApplication.cs:65
I have no idea what does this mean. I have searched and many people got this issues in several situations.But I didn't something like my scenerio.How to solve this?Any help is appreciated.
I thought I'd just finished an app, however when I build for iOS, there is a certain section that is returning a
"NullReferenceException: A null value was found where an object instance was required."
Here is the Xcode error:
NullReferenceException: A null value was found where an object instance was required.
at nextSetAmount.nextButtonCelestials (Boolean onOff) [0x00000] in <filename unknown>:0
at celestialDialogueInstantiator.setActive (Int32 indexToTurnOn) [0x00000] in <filename unknown>:0
at UnityEngine.Events.UnityEvent.Invoke () [0x00000] in <filename unknown>:0
at UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) [0x00000] in <filename unknown>:0
at UnityEngine.EventSystems.StandaloneInputModule.ProcessTouchPress (UnityEngine.EventSystems.PointerEventData pointerEvent, Boolean pressed, Boolean released) [0x00000] in <filename unknown>:0
at UnityEngine.EventSystems.StandaloneInputModule.ProcessTouchEvents () [0x00000] in <filename unknown>:0
at UnityEngine.EventSystems.StandaloneInputModule.Process () [0x00000] in <filename unknown>:0
UnityEngine.EventSystems.ExecuteEvents:Execute(GameObject, BaseEventData, EventFunction`1)
UnityEngine.EventSystems.StandaloneInputModule:ProcessTouchPress(PointerEventData, Boolean, Boolean)
UnityEngine.EventSystems.StandaloneInputModule:ProcessTouchEvents()
UnityEngine.EventSystems.StandaloneInputModule:Process()
(Filename: currently not available on il2cpp Line: -1)
NullReferenceException: A null value was found where an object instance was required.
at audioManagerCreate.Start () [0x00000] in <filename unknown>:0
and here are the respective scripts that it's talking about:
nextSetAmount
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class nextSetAmount : MonoBehaviour {
public GameObject slider;
public GameObject dialogueManager;
public GameObject celestialManager;
public GameObject audioManager;
public GameObject celestialObject;
// Use this for initialization
public void nextButtonDialogue (bool onOff) {
if(onOff == true)
{
dialogueManager.GetComponent<celestialDialogueInstantiator>().makeDialogue(Mathf.RoundToInt(slider.GetComponent<Slider>().value));
}
}
public void nextButtonCelestials (bool onOff) {
if(onOff == true)
{
audioManager.SetActive(true);
AudioListener.pause = true;
for(int i = 0; i < slider.GetComponent<Slider>().value; i++)
{
Transform celestialDialogue = GameObject.Find("celestialDialogue"+i).gameObject.transform;
string celestialName = celestialDialogue.GetChild(2).GetComponent<Text>().text;
float celestialBodyDistance = celestialDialogue.GetChild(4).GetComponent<Slider>().value;
float celestialOrbitalFrequency = celestialDialogue.GetChild(6).GetComponent<Slider>().value;
float celestialRotationalFrequency = celestialDialogue.GetChild(8).GetComponent<Slider>().value;
float celestialBodyDiameter = celestialDialogue.GetChild(10).GetComponent<Slider>().value;
float celestialBodyTemperature = celestialDialogue.GetChild(12).GetComponent<Slider>().value;
// Instantiate celestialObject prefab
var instantiatedCelestial = Instantiate(celestialObject, new Vector3(0,0,0),Quaternion.identity);
// Define properties script for ease of code
var celProps = instantiatedCelestial.GetComponent<celestialProperties>();
// Set name of instantiated prefab
instantiatedCelestial.gameObject.name = ("celestialObject"+i);
// Set parent of instantiated prefab
instantiatedCelestial.transform.SetParent(GameObject.Find("celestialManager").transform);
// Randomise properties of the instantiated celestialObject prefab
celProps.celestialName = celestialName;
celProps.celestialID = i;
// Set distance from centre as i (celestialObject number) + a float value. This ensures that 0 is closest, and x where x = amountOfCelestials is the furthest.
celProps.celestialBodyDistance = celestialBodyDistance;
celProps.celestialOrbitFrequency = celestialOrbitalFrequency;
celProps.celestialRotationalFrequency = celestialRotationalFrequency;
celProps.celestialBodyDiameter = celestialBodyDiameter;
celProps.celestialBodyTemperature = celestialBodyTemperature;
celProps.celestialOrbitAxis = new Vector3(0,1,0);
// Store initial values for these two so that scaling doesn't multiply by itself
celProps.celestialInitOrbitFrequency = celProps.celestialOrbitFrequency;
celProps.celestialInitRotationalFrequency = celProps.celestialRotationalFrequency;
}
}
}
}
celestialDialogueInstantiator
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
public class celestialDialogueInstantiator : MonoBehaviour {
// Define prefab to instantiate
public GameObject celestialDialogue;
public GameObject systemNameCreate;
public GameObject parent;
public int dialogueID;
public GameObject slider;
public GameObject[] celestialObjects;
// Use this for instantiation
public void makeDialogue (int sliderValue)
{
// For loop that instantiates x amount of dialogues where x = argument.
for(int i = 0; i < sliderValue; i++)
{
var instantiatedDialogue = Instantiate(celestialDialogue,transform.position, Quaternion.identity);
instantiatedDialogue.transform.SetParent(GameObject.Find("createDialogue").gameObject.transform, false);
instantiatedDialogue.SetActive(false);
instantiatedDialogue.name = "celestialDialogue"+i;
instantiatedDialogue.GetComponent<dialogueID>().ID = i;
if (i == 0)
{
instantiatedDialogue.SetActive(true);
}
}
}
public void setActive(int indexToTurnOn)
{
// Turn on next dialogue
if(indexToTurnOn != slider.GetComponent<Slider>().value)
{
GameObject.Find("createDialogue").gameObject.transform.GetChild(indexToTurnOn).gameObject.transform.localScale = new Vector3(0,0,0);
GameObject.Find("createDialogue").gameObject.transform.GetChild(1+indexToTurnOn).gameObject.SetActive(true);
}
// When the last next button is pressed.
else
{
// Set active createCelestials GUI panel
Resources.FindObjectsOfTypeAll<GameObject>().FirstOrDefault(g=>g.CompareTag("Finish")).gameObject.SetActive(true);
GameObject.Find("System Title").gameObject.GetComponent<Text>().text = GameObject.Find("dialogueManager").GetComponent<celestialDialogueInstantiator>().systemNameCreate.GetComponent<Text>().text;
this.gameObject.GetComponent<nextSetAmount>().nextButtonCelestials(true);
AudioListener.pause = false;
setAllInactive(parent.transform,true);
}
}
// Sets all inactive if value = true
public void setAllInactive (Transform transform, bool value)
{
foreach (Transform child in transform)
{
if(value == true)
{
child.gameObject.SetActive(!value);
}
}
}
}
audioManagerCreate
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Audio;
public class audioManagerCreate : MonoBehaviour {
public AudioMixer systemMixer;
public Slider slider;
// Use this for initialization
void Start ()
{
// Find amount of celestials in scene
// For each celestial, assign corresponding audio mixer group based on celestialID/i (essentially the same value)
for(int i = 0; i < slider.value; i++)
{
GameObject celestialObject = GameObject.Find("celestialObject"+i).gameObject;
string masterMix = "Master";
celestialObject.GetComponent<AudioSource>().outputAudioMixerGroup = systemMixer.FindMatchingGroups(masterMix)[i+1];
}
}
}
I'm not the best at troubleshooting, but I assume that the problem exists because it cannot find the gameObject that GameObject.Find() is pointing to. It works completely fine in Unity and finds the objects without fault.
The only constant that I can see is that I'm trying to find an object based on its name + i where i is the for-int loop ID. I need to do this because its looking for objects that don't exist until they're are instantiated, and whose names are based on their ID from the for-int loop in their instantiation script.
I faced a very similar problem and it was driving me crazy, since there was no sense on the fact that GameObject.Find was working pretty well on Simulator, but returning a NullReferenceException on iOS build. I had tried a lot of things and I had no success at all...
Then, I got an insight... the problem wasn't GameObject.Find method itself and I explain you why:
When we are about to generate a build in Build Settings, we need to include the Scenes we want to add to the build. Look at the picture below:
That is, SpaceScene scene was being executed on the code, but it wasn't included in the build... so its objects had not been loaded (of course). That's why GameObject.Find was returning null.
My solution was to include the scene SpaceScene in the build and everything ran as it was supposed to be.
Here's my code;
I've looked it up online, but still unable to fix it.
Please show me a fixed version of the code, thank you so much! I've been staring at the screen for half 'n' hour and still can't figure this out!
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D car1Texture;
Vector2 car1Position = new Vector2(200f, 100f);
Texture2D background;
Rectangle mainFrame;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
//Change the resolution to 800x600
graphics.PreferredBackBufferWidth = 1000;
graphics.PreferredBackBufferHeight = 800;
graphics.ApplyChanges();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the background content.
background = Content.Load<Texture2D>("roadscan");
// Set the rectangle parameters
mainFrame = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
spriteBatch = new SpriteBatch(GraphicsDevice);
car1Texture = Content.Load<Texture2D>("car1");
}
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
KeyboardState keyboard = Keyboard.GetState();
GamePadState gamePad = GamePad.GetState(PlayerIndex.One);
if (keyboard.IsKeyDown(Keys.Left) || gamePad.DPad.Left == ButtonState.Pressed)
{
ballPosition.X -= 3f;
}
if (keyboard.IsKeyDown(Keys.Right) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.X += 3f;
}
if (keyboard.IsKeyDown(Keys.Up) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.Y += 3f;
}
if (keyboard.IsKeyDown(Keys.Down) || gamePad.DPad.Right == ButtonState.Pressed)
{
ballPosition.Y -= 3f;
}
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// Draw the background.
// Start building the sprite.
spriteBatch.Begin();
// Draw the background.
spriteBatch.Draw(background, mainFrame, Color.White);
// End building the sprite.
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
Remove the extra brace above the UnloadContent method
Right here:
// TODO: use this.Content to load your game content here
}<-------Delete this guy!!!
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
You've got one to many closing curly braces.
protected override void LoadContent()
{
// snip
} //close method
// TODO: use this.Content to load your game content here
} //close class
You accidentally close the class half way through, just removing the curly brace will fix things. This is common when you haven't shrunk or removed the default comment blocks as they tend to get in the way after you've learnt what all the basic methods do.