Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by eliotkimmelcentillion · Aug 03, 2021 at 01:16 AM · inspectorprefabsdrag-and-dropreferencing

Getting a Reference to a Prefab Dragged into Scene

I'm making a game that is hex-tile-based. All objects in the game grid inherit from a script called GridObject (as seen below). It defines each object's position in the grid. I have another script called MapManager (also below), which is attached to a single object in the scene. It has an array that stores references to objects based on their position in the grid, so that the objects can interact with each other. For example, if an enemy wanted to check two spaces in front of it to detect the player, it would call a method of this map manager to "ask" for what object existed at that position. When objects move, or are first spawned in, their positions in this array need to be updated.

Grid objects are created with the static method Create(). They are not only instantiated, but are assigned new grid positions and will be assigned other important data as this game project evolves.

More Specifically, I want these grid objects to enter the game in one of two ways: 1. During runtime, the Create() method gets called in some script; the object is instantiated and stored in the array of grid positions 2. I drag a prefab from the assets folder into the scene; the game starts and the Start() method is called on this object; a reference to the object is stored in the array of grid positions.

This first way works fine. The instantiated object has its Init() method called, and a reference to this instance is stored in the map manager's array, using the AddPositionInGrid() method. This position can be updated during runtime without issue. However, problems arise when I drag a prefab object into the scene, and it calls its Init() method. For whatever reason, when I try to pass a reference to this object into AddPositionInGrid(), I get an error: NullReferenceException: Object not set to an instance of an object Do these prefab objects I dragged into the scene not count as instances? If so, why? How can I set things up so that I can just drag these objects in and then store valid references to them? Maybe my system for keeping track of objects is not optimal. If so, I'm open to criticism. Here's all my relevant code:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using StaticFuncs;
 
 public class GridObject : MonoBehaviour
 {
     public bool draggedIntoScene = false;
     public int q;
     public int r;
     private Transform transform;
     private MapManager mapManager;
 
     void Start()
     {
         if (draggedIntoScene)
         {
             Init(q,r);
         }
     }
 
     public static GridObject Create(int _q, int _r, GridObject baseGridObject)
     {
         GridObject grObj = Instantiate(baseGridObject) as GridObject;
         grObj.Init(_q, _r);
         return grObj;
     }
 
     public void Init(int _q, int _r)
     {
         //Debug.Log("Initializing GridObject " + this.name + " at q: " + _q.ToString() + ", r: " + _r.ToString());
         q = _q;
         r = _r;
 
         transform = gameObject.GetComponent(typeof(Transform)) as Transform; //init transform field
         mapManager = MapManager.Instance;
 
         mapManager.AddPositionInGrid(this);
 
         UpdateHexToWorldPosition();
     }
 
     public void MoveToPosition(int newQ, int newR)
     {
         mapManager.RemovePositionInGrid(this);
         q = newQ;
         r = newR;
         mapManager.AddPositionInGrid(this);
         UpdateHexToWorldPosition();
     }
 
     private void UpdateHexToWorldPosition() //figures out where to draw the object in the world based on its grid position
     {
         transform.position = new Vector3(Statics.flat_hex_to_pixel_x(q, r, MapManager.hexSize), 0f, Statics.flat_hex_to_pixel_z(r, MapManager.hexSize));
     }
 
     void CheckGridSpace()
     {
         //not worrying about this one yet
     }
 }
 
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEditor;
 using StaticFuncs;
 
 //object that holds info for terrain and draws it
 public class MapManager : MonoBehaviour
 {
     //singleton: all grid objects should be able to access the one instance of this class
     private static MapManager _instance;
     public static MapManager Instance {get {return _instance;}}
 
     public static int gridSize = 16;
     public static float hexSize = 2f; //diameter!
 
     public GridObject[,] gridPositions;
     public GridObject terrainPrefab;
 
     void Start()
     {
         generate();
     }
 
     void generate()
     {
         gridPositions = new GridObject[gridSize, gridSize];
         GridObject.Create(1,1, terrainPrefab);
         GridObject.Create(0,0, terrainPrefab);
         GridObject.Create(0,1, terrainPrefab);
         GridObject.Create(1,0, terrainPrefab);
     }
 
     public void RemovePositionInGrid(GridObject grObject) {gridPositions[grObject.q, grObject.r] = null;}
 
     public void AddPositionInGrid(GridObject grObject) {gridPositions[grObject.q, grObject.r] = grObject;}
 
     void Awake()
     {
         if (_instance != null && _instance != this)  {
             Destroy(this.gameObject);
         }
         else  {
             _instance = this;
         }
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by AtiyehNorouzi22 · Aug 03, 2021 at 05:56 AM

prefabs losses references of objects in scenes. you have to find gameobject by tag or name or type in runtime. the better way is to store the scene gameobject into prefabs folder in your assets and use it. hope this helps

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

135 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Unable to drop GameObject in Inspector of other GameObject 0 Answers

Drag and Drop onto Array of Custom Objects 0 Answers

Is there a way to prevent non-prefab objects from being linked in the inspector? 0 Answers

How to create a script reference in the inspector that can accept any class of script? 1 Answer

The variable has not been assigned (but it has) 10 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges