I have been trying to aimlessly make a unity game around a 3d aim trainer and I have been trying to set up the targets that pop up. For now, I just wanted to create targets that pop up once every second at a maximum of 3 targets at one time ever. I have already set up the random spawn of the targets and the removal of them with the help of raycast shooting and made a max of 3 targets, however, to make the max of 3 targets I used an integer with a simple targetCount += 1 and the deletion of the target is being done on a different script as seen below. My problem is making the targets respawn once being shot after spawning the first 3 targets. I tried to use getComponent to reach the targetCount variable in my Target code to just simply targetCount -= 1 every time I delete a target so that as long as the variable doesn't reach 3, it will continue to spawn targets however I was having some troubles. Please let me know if you have any ideas This is my target spawning code using System.Collections; using System.Collections.Generic; using UnityEngine;  public class GenerateEnemies : MonoBehaviour {     public GameObject theTarget;     public float xPos;     public float yPos;     public int targetCount = 0;      void Start(){         StartCoroutine(TargetDrop());     }      IEnumerator TargetDrop()     {         while (targetCount &lt; 3)         {             xPos = Random.Range(-6, 11.5f);             yPos = Random.Range(2.4f, 9);             Instantiate(theTarget, new Vector3(xPos, yPos, 13.5f), Quaternion.identity);             yield return new WaitForSeconds(1);             targetCount += 1;         }     } }  And this is my Code attached to my target using System.Collections; using System.Collections.Generic; using UnityEngine;  public class Target : MonoBehaviour, IDamageable {     [SerializeField] private TargetStats targetStats;      private int currentHealth;     /*     public GenerateEnemies generateEnemies;      private void Awake()     {         generateEnemies = GetComponent&lt;GenerateEnemies&gt;();     }     */     private void Start()     {         currentHealth = targetStats.maxHealth;     }      public void DealDamage(int damage)     {         currentHealth -= damage;         CheckIfDead();     }          private void CheckIfDead()     {         if(currentHealth &lt;= 0)         {             Destroy(gameObject);             /*GenerateEnemies.targetCount -= 1;*/         }     } }
17044
I need to access a variable from another script in Unity, but I can't figure it out. Script:  public class move : MonoBehaviour { public float speed; // Use this for initialization void Start () {  }  // Update is called once per frame void Update () {     transform.position += Vector3.left * Time.deltaTime * speed; }  }   I want to access the variable speed in another script, but I can't. Any help will be appreciated :)
89399
I am making a multiplayer parkour map on bedrock edition, and I have it set up where when a player steps on a grass block they die. But when a player steps on a grass block it just kills anyone who touches it.  First: A repeat command block (set to always active and unconditional)   execute @e [type=player] ~ ~ ~ testforblock ~ ~-1 ~ grass   And then I have a chain command block (set to conditional and always active)  kill @e [type=player]   And it does work..... IF in singleplayer only. (which is not at all what I want)  Thank y'all in advance.
93861
How is it possible that a create an item counter in unity? My current Scripts - Counter.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;  public class Counter : MonoBehaviour {     public int ScoreAmount;     private Text ScoreText;     // Start is called before the first frame update     void Start()     {         ScoreText = GetComponent&lt;Text&gt;();         ScoreAmount = 0;     }      // Update is called once per frame     void Update()     {         ScoreText.text = &quot;&quot; + ScoreAmount;     }  Where I have a text UI called ScoreText ItemPickup.cs using System.Collections; using System.Collections.Generic; using UnityEngine;  public class ItemPickup : MonoBehaviour {     void OnTriggerEnter2D(Collider2D other)     {         if (other.CompareTag(&quot;Fruit&quot;))          {             Debug.Log(&quot;Picking up fruit...&quot;);             Counter.ScoreAmount += 1;         }       } }  But I get this error &quot;Assets/ItemPickup.cs(12,13): error CS0120: An object reference is required for the non-static field, method, or property 'Counter.ScoreAmount'&quot;  How do I fix it please?
94362
I am making a game in Unity 5 in C# and I need to make the terrain infinite. I have tried to make it infinite but it just keeps spawning the terrain too much times and then the game crashes. Does someone know how I can make the terrain infinite? Here is my  code.  using System.Collections; using System.Collections.Generic; using UnityEngine;  public class TerrainScript : MonoBehaviour {     public Transform PlayerTransform;     private float SpawnZ = 4139f;     public GameObject[] prefabs;     private float RoadLength = 2.2f;     private int amountRoads = 6;     private List&lt;GameObject&gt; roadList;      public void Start()     {         roadList = new List&lt;GameObject&gt;();     }     public void Update()     {         if(PlayerTransform.position.z &gt; (SpawnZ - amountRoads * RoadLength))         {             spawnTile(0);         }     }      public void spawnTile(int index)     {         GameObject go;         go = Instantiate(prefabs[index]) as GameObject;         go.transform.SetParent(transform);         go.transform.position = Vector3.forward * SpawnZ;         SpawnZ += RoadLength;     } }
121434
I have a siteRegistrationController which is creating portal users as below:  Registration Controller:  public class SiteRegistrationController{      public void createPortalUser(){         //There is code to populate the values for variables u and acc.         String userId = Site.createPortalUser(u, acc.Id,null,false);             System.debug('userId is '+userId);     }  }   I am trying to test the above code and below is in my test class:  Test Class:  public class SiteRegistrationController_TEST{          SiteRegistrationController controllerObj = new SiteRegistrationController();          User guestUserObj = new User(username='testsfsdfsd@test.com',                                 IsActive=TRUE,                                 FirstName='test',                                 LastName='test',                                 Email='testsdfsd@test.com',                                 Alias='test',                                 timezonesidkey='America/Los_Angeles',                                 localesidkey='en_US',                                 emailencodingkey='UTF-8',                                 languagelocalekey='en_US');         insert guestUserObj;          System.runAs(guestUserObj){             controllerObj.createPortalUser();            } }   Site.createPortalUser is always returning null in test context.    -- This post is also about same problem but no solution here.  -- This post suggests that use the System.runAs(guestUser) but does not specify how to create guest user.   If any body has solution for this..Please help me. Thanks in Advance!
100133
Please don't mark this as a duplicate of my previous question which was asked anonymously. this is a reattempt because i cannot edit the first attempt.  What I have so far is:  - randomly generated tile set with items on SOME tiles - one creature spawner that spawns up to 5 creatures which can be controlled by the player - the ability for creatures to pick up items and bring them back to the spawn and store them for later use  What I am noticing is when i launch the game, it doesnt always show all the sprites. Sometimes the spawner is missing, or the creatures, or the GUI. ANd when things DO appear, if i tell the creatures to pick up anything, other items on the ground randomly appear and disappear. even the spawn sometimes disappears! what I do notice is that when i have multiple creatures, some will disappear when crossing invisible lines but not all of them. i forced two creatures to go east at the same speed and time, and one vanished and the other didnt.  If you have any ideas as to what might be causing this, please let me know. if you have any questions, i'll try to edit to appease you.  thanks for reading!  I have my draw method like this:  GraphicsDevice.Clear(Color.CornflowerBlue);  // TODO: Add your drawing code here  spriteBatch.Begin(SpriteSortMode.BackToFront,           null, null, null, null, null,           camera.GetTransformation());            worldEntity.Draw(spriteBatch);  guiManager.DrawGUI(spriteBatch);  spriteBatch.End();  base.Draw(gameTime);   for the world entity...  its draw method systematically goes through each tile in the world and calls its draw method. the tile draws itself using  Vector2 topLeftOfSprite = new Vector2(this.X, this.Y); Color tintColor = Color.White; spriteBatch.Draw(tileTexture, topLeftOfSprite, tintColor);   and then proceeds to call the draw method of any items on it.  creatures and items have very similar draw methods.  the gui also draws itself in a similar fashion.  what i DO notice is that ive NEVER seen ground tiles vanish, only the items on them or creatures in the world. Could it be their Z isn't set appropriately?
46601
Why can't I snap the point I chose to the target point.  I tried for a long time to do this, but no use!  Could some help me? Thanks !
86697
I bought a book called Programming game AI by example and I am trying to implement the arrive steering behavior. The problem I am having is that my objects oscillate around the target position; after oscillating less and less for awhile they finally come to a stop at the target position. Does anyone have any idea why this oscillating behavior occur? Since the examples accompanying the book are written in C++ I had to rewrite the code into C#. Below is the relevant parts of the steering behavior:  private enum Deceleration {     Fast = 1,     Normal = 2,     Slow = 3 }  public MovingEntity Entity { get; private set; }  public Vector2 SteeringForce { get; private set; }  public Vector2 Target { get; set; }  public Vector2 Calculate() {     SteeringForce.Zero();      SteeringForce = SumForces();      SteeringForce.Truncate(Entity.MaxForce);      return SteeringForce; }  private Vector2 SumForces() {     Vector2 force = new Vector2();      if (Activated(BehaviorTypes.Arrive))     {         force += Arrive(Target, Deceleration.Slow);          if (!AccumulateForce(force))             return SteeringForce;     }      return SteeringForce; }  private Vector2 Arrive(Vector2 target, Deceleration deceleration) {     Vector2 toTarget = target - Entity.Position;      double distance = toTarget.Length();      if (distance &gt; 0)     {         //because Deceleration is enumerated as an int, this value is required         //to provide fine tweaking of the deceleration..         double decelerationTweaker = 0.3;          double speed = distance / ((double)deceleration * decelerationTweaker);          speed = Math.Min(speed, Entity.MaxSpeed);          Vector2 desiredVelocity = toTarget * speed / distance;          return desiredVelocity - Entity.Velocity;     }      return new Vector2(); }  private bool AccumulateForce(Vector2 forceToAdd) {     double magnitudeRemaining = Entity.MaxForce - SteeringForce.Length();      if (magnitudeRemaining &lt;= 0)         return false;      double magnitudeToAdd = forceToAdd.Length();      if (magnitudeToAdd &gt; magnitudeRemaining)         magnitudeToAdd = magnitudeRemaining;      SteeringForce += Vector2.NormalizeRet(forceToAdd) * magnitudeToAdd;      return true; }   This is the update method of my objects:  public void Update(double deltaTime) {     Vector2 steeringForce = Steering.Calculate();      Vector2 acceleration = steeringForce / Mass;      Velocity = Velocity + acceleration * deltaTime;      Velocity.Truncate(MaxSpeed);      Position = Position + Velocity * deltaTime; }   If you want to see the problem with your own eyes you can download a minimal example .  Thanks in advance.
83286
In the game engine, my object needs to point at a target. How can I get it to aim at something that is constantly moving in unpredictable patterns? The constraints actuator does not have a "track to" that I can see however the 'track to' is exactly the effect I want. I'm using v. 2.71.
101123
Right now, when I spawn a shootable object, it goes like this:    Because I just set it's angle to this:  float aimAngle = (float) Math.atan2(velocity.y, velocity.x); bullet.setBodyAngle(aimAngle);   I want it to be like this:    I think I should use angular velocity or torque, but I have no idea how. I can't just set it's angle like in previous code every frame, because it makes physics collisions glitch.
56441
I am currently programming a trigger on Opportunities.   I created a test class for this and in my Sandbox I created an account, contact and opportunity. When I try to reference them   Opportunity Opp = [SELECT id from Opportunity where name = 'Test1'];    and then start my   Test.startTest();         Opp.StageName = 'PO in (100%)';          update Opp;         Test.stopTest();   It just errors and shows that Opp returns 0 rows. However when I paste my first bit of code in 'Execute Anonymous' it returns a row and the correct info.   Does this mean I have to create an account, contact, quote and all necessary fields in my test class?
8224
Since many users are facing the NullReferenceException: Object reference not set to an instance of an object error in Unity, I thought that it would be a good idea to gather from multiple source some explanation and ways to fix this error.  Symptoms I am getting the error below appearing in my console, what does it mean and how do I fix it?  NullReferenceException: Object reference not set to an instance of an object
67365
How to implement Unit Test at Unity3D.   I wonder if it would be possible to extend the Unity editor to have some sort of testing framework in it.    Is there any guideline to implement it? Any reference like book, blog? Any working example or project?
92666
Seem to have exhausted google looking for an answer to a VERY bullet simple code that should work.  void onCollisionEnter(Collision col) {     print ("hit " + col.gameObject.name);     Destroy (gameObject);     }   Bullet object has the above script, SphereCollider (radius a lot bigger than object), RigidBody, not a trigger, not kinematic, is travelling slow. All checked during runtime.  When it hits a wall (Box collider), it just bounces off but no collisionEnter code is ran.  Debug console bubble is on.
37089
I'm making a game where things randomly generate. It used to work, but now all the sudden they keep spawning in the same area every time. does anybody know a fix?
66105
When I use this RenderTarget:  renderTarget = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width,     GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color, DepthFormat.Depth24);   and draw something to it:  graphicsDevice.SetRenderTarget(renderTarget); // some drawing code here graphicsDevice.SetRenderTarget(null);   and then when I want to continue with drawing depth buffer seams to be clean. Why? Is possible to save it for future use?
110698
I am trying to make a top down shooter that could potentially have hundreds of objects at once at one point. I need to check collision with projectiles, walls, and enemies. I am currently using ArrayLists which probably won't suffice later on and was wondering if someone had a good method or knows a good method for checking all of those objects at once. This is going to be a game for smartphones and is built in java. Any ideas would be great or if you could point me in some direction that would be fantastic.  Thanks in advance!