• 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
Question by aLovedHater · Mar 17, 2015 at 09:06 PM · errorwaypoints

how to set a variable in prefabs or use an object in the hierarchy/prefab section in my script

So, i have a spawner script and a waypoint movement script (Spawner.cs and WayPointAI.cs)

Spawner -

  using UnityEngine;
     using System.Collections;
     
     public class Spawner : MonoBehaviour 
     {
     
         public Transform spawnPoint;
         public Transform spawnObject;
         public int spawnTotal;
         public float timeBetweenSpawns;
     
         // Use this for initialization
         void Start () 
         {
             StartCoroutine (SpawnGameObject());
         }
         
         // Update is called once per frame
         void Update () 
         {
         
         }
         IEnumerator SpawnGameObject ()
         {
             for( var x = 0; x < spawnTotal; x++)
             {
                 Instantiate(spawnObject, spawnPoint.position, spawnPoint.rotation);
                 yield return new WaitForSeconds(timeBetweenSpawns);
             }
         }
     }
 

My spawner script will spawn a NPC prefab on the spawner object.

Waypoint movement script -

     // Use this for initialization
     void Start () 
     {
         //find each waypoint object in the scene when game is loaded
         wayPoint [0] = GameObject.Find("WayPoint 1").transform;
 
     }
     
     // Update is called once per frame
     void Update () 
     {
         // once npc reaches last waypoint, it is destroyed
         if(currentWayPoint == 1)
         {
             Destroy (this.gameObject);
         }
         else
         {
             walk();
         }
 
     }
     //makes npc move
     void walk()
     {
         //facing direction
         //npc looks at next waypoint
         Quaternion rotation = Quaternion.LookRotation(wayPoint[currentWayPoint].position - transform.position);
         //how fast npc turns
         transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime*rotationSpeed);
         
         //movement
         Vector3 wayPointDirection = wayPoint[currentWayPoint].position - transform.position;
         float speedElement = Vector3.Dot(wayPointDirection.normalized, transform.forward);
         float speed = accelerate * speedElement;
         transform.Translate(0,0,Time.deltaTime*speed);
         }
 
     void OnTriggerEnter(Collider collider)
     {
         if (collider.tag == "WayPoint 1") 
             Destroy (this.gameObject);
             //currentWayPoint = 1;
             //currentWayPoint++;
     }
 
 }



After Spawner.cs pulls an NPC from the prefabs and then spawns it on the Spawner object, WayPointAI will move the NPC fromt he spawner, to WayPoint 1 (object in the hierarchy). once the NPC reaches WayPoint 1, it despawns (is destroyed) the problem here is that i can't set the WayPoint element 0 to an object when it's in the prefab folder (when i drag the WayPoint1 object from the hierarchy onto the WayPoint element 0 variable in the NPC's WayPointAI script (the npc is in the hierarchy), i get an error sign and it doesn't let me set the variable to the object in the hierarchy. you may think "why is this a problem? the NPC is set to walk to an object named 'WayPoint 1', so why do you need to set the variable to the WayPoint 1 object too?". That's a good question. the reason i want to be able to set the variable is because i want to make multiple spawners that go to their own WayPoint 1's. so there's two ways i can solve this problem: first, i could make it so i can set the variable on the NPC's WayPointAI script in the prefabs folder and everything will be golden, or i can waste time and space by making another 50 identical scripts with the two lines with "WayPoint 1" in them to "WayPoint 2" and "WayPoint 3", and so on. but i would really prefer it if i could just set a variable on the NPC in the prefab folder. does anyone know how? help would be greatly appreciated! and if you're confused on soemthing just ask me and i'll try to be more specific and detailed.

Thanks in advance!

Comment

People who like this

0 Show 2
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
avatar image NoseKills · Mar 18, 2015 at 07:02 AM 0
Share

first, i could make it so i can set the variable on the NPC's WayPointAI script in the prefabs folder and everything will be golden

But then you'd have to make 50 of these prefabs with different waypoints assigned to them and somehow select which one to spawn every time, right?

The objects in hierarchy/scene are actual existing object instances. The objects in project view/prefabs are just blueprints for making objects. It doesn't make sense that a blueprint of something would reference a real world object (e.g. this is the blueprint for building a house... but only for a certain Jack J. Johnson in Wales). What if you'd spawn an object like this to a different scene that doesn't have the objects it references (waypoints) ?

This is the fundamental problem you are having.

So depending on what exactly you want, I think you'll have to come up with an "AI" that selects the waypoint for each NPC in their Start() method based on some rules.

avatar image aLovedHater · Mar 20, 2015 at 04:25 PM 0
Share

public Transform[] wayPoint = new Transform[1]; //create an array for storing each waypoint

it's public, could it be anything else?

2 Replies

· Add your reply
  • Sort: 
avatar image

Answer by Baste · Mar 18, 2015 at 07:48 AM

Put the waypoint(s) on the spawner, and drag and drop them from the hireachy.

Then, when you spawn a NPC, pass the waypoints to it:

 for( var x = 0; x < spawnTotal; x++)
 {
     GameObject spawned = Instantiate(spawnObject, spawnPoint.position, spawnPoint.rotation) as GameObject;
     WaypointMovement mover = spawned.GetComponent<WaypointMovement>();
     mover.waypoints = waypoints;
     yield return new WaitForSeconds(timeBetweenSpawns);
 }

You should also try to get rid of all string comparrison and GameObject.Find - they're incredibly inflexible, as any tiny misspelling (like an extra space) will break your code. GameObject.Find is also really slow.

Comment
awardell

People who like this

1 Show 5 · 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
avatar image aLovedHater · Mar 19, 2015 at 10:55 PM 0
Share

i'm a little confused, so i could reference my waypointmovement script in my spawner script and then it would look like this?

 for( var x = 0; x < spawnTotal; x++)
 {
 GameObject spawned = Instantiate(spawnObject, spawnPoint.position, spawnPoint.rotation) as GameObject;
 WaypointMovement walk = spawned.GetComponent<WaypointMovement>();
 walk.wayPoint = wayPoint;
 yield return new WaitForSeconds(timeBetweenSpawns);
 }

avatar image Baste · Mar 20, 2015 at 12:06 AM 0
Share

Pretty much.

avatar image aLovedHater · Mar 20, 2015 at 12:45 AM 0
Share

i get an error on line 5 saying "the name 'wayPoint' does not exit exist in the current context" why would it say that? and i looked some stuff up about how to replace my string comparisons and gameobject.find's and people said to pass the object reference, is there any scripting API where i could learn what that is? i couldn't find any.

avatar image awardell · Mar 20, 2015 at 01:10 AM 0
Share

Is wayPoint public or private? If it's private and you're trying to access it from Spawner, you'll get that error.

avatar image Baste · Mar 20, 2015 at 08:37 AM 0
Share

You need to actually have a public waypoint array on your spawner, and send that to the walker:

 public class Spawner : MonoBehaviour {

     public Transform[] waypoint; //populate this from the inspector

     ...

     IEnumerator SpawnGameObject () {
         for( var x = 0; x < spawnTotal; x++) {
             GameObject spawned = Instantiate(spawnObject, spawnPoint.position, spawnPoint.rotation) as GameObject;
             WaypointMovement walk = spawned.GetComponent<WaypointMovement>();
             walk .wayPoint = wayPoint;
             yield return new WaitForSeconds(timeBetweenSpawns);
         }
     }
 }
avatar image

Answer by aLovedHater · Mar 20, 2015 at 11:30 PM

so my spawner currently looks like this -

 using UnityEngine;
 using System.Collections;
 
 public class Spawner : MonoBehaviour 
 {
 
     public Transform spawnPoint;
     public Transform spawnObject;
     public int spawnTotal;
     public float timeBetweenSpawns;
     private WayPointAI wayPointAI;
     public Transform[] waypoint;
 
     // Use this for initialization
     void Start () 
     {
         StartCoroutine (SpawnGameObject());
     }
     
     // Update is called once per frame
     void Update () 
     {
     
     }
     IEnumerator SpawnGameObject ()
     {
         for( var x = 0; x < spawnTotal; x++)
         {
             GameObject spawned = Instantiate(spawnObject, spawnPoint.position, spawnPoint.rotation) as GameObject;
             WayPointAI walk = spawned.GetComponent<WayPointAI>();
             walk.wayPoint = waypoint;
             yield return new WaitForSeconds(timeBetweenSpawns);
         }
     }
 }

in my hierarchy i have Spawner's waypoint variable set to the waypoint, (array size of 1) and Waypoint movement's waypoint variable is set to the waypoint as well (also with an array size of 1). everything runs fine but when i run it, it will spawn in one NPC that doesn't move and i'll get the error "NullReferenceException: Object not set to an instance of an object, Spawner+c__Iterator0.MoveNext ()"

and it will point me to this line of code -

 WayPointAI walk = spawned.GetComponent<WayPointAI>();

Comment

People who like this

0 Show 0 · 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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

error CS0161: not all code paths return a value 2 Answers

Error when accessing variables from another script: NullReferenceException: Object Reference not set to an instance of an object.. 0 Answers

BCE0044 error: OnControllerColliderHit 2 Answers

Has anyone tried opening a Unity Reflect project in Unity Pro? 0 Answers

MonoDevelop Error Underlinings for *.js 0 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