title: Why is my ad not showing?

text:
# Question
Title: Why is my ad not showing?
My ad does not appear. I want to click the button and have an ad appear.

```
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;

public class GameOverControl : MonoBehaviour {
  InterstitialAd interstitital;

  [SerializeField]
  private AudioSource OverSes;

  void Start () {
    OverSes.Play ();
    MobileAds.Initialize ("");

    RequestinterstitialAd ();
  }

  public void Tekrar () {
    SceneManager.LoadScene ("BonyBony");
    ShowinterstitialAd ();
  }

  public void MenuyeDon () {
    SceneManager.LoadScene ("MainMenu");
    ShowinterstitialAd ();
  }

  private void RequestinterstitialAd() {
    interstitital = new InterstitialAd ("");
    AdRequest adRequest = new AdRequest.Builder ().Build ();
    interstitital.LoadAd (adRequest);
  }

  private void ShowinterstitialAd() {
    if (interstitital.IsLoaded ()) {
      interstitital.Show ();
    }
  }
}

```

# Answer
The problem is within this method

```
public void MenuyeDon () {
    SceneManager.LoadScene ("MainMenu");
    ShowinterstitialAd ();
}

```

You are loading a new scene, then showing the ad. The code below the loading scene never gets executed. What you need to do is something like this:

```
void Start () {
    OverSes.Play ();
    MobileAds.Initialize ("");

    // This assigns the method HandleOnAdClosed to execute when the ad is closed
    this. interstitital.OnAdClosed += HandleOnAdClosed;

    RequestinterstitialAd ();
}

public void MenuyeDon () {
    if (interstitital.IsLoaded ()) {
        interstitital.Show ();
    } else {
        SceneManager.LoadScene ("MainMenu");
    }
}

// This will be called when the ad is closed
public void HandleOnAdClosed(object sender, System.EventArgs args)
{
    SceneManager.LoadScene ("MainMenu");
}

```

What this will do is when the button is clicked, it will show the ad, then when the ad is closed, it loads the scene.
> 0 votes

---
Tags: unity, unity-ads
---


# Question
Title: GML: check ds_queue or ds_stack for equality (identical contents)
Is there a nondestructive way to check whether two queues or stacks contain identical values? For example:

```
foo=ds_queue_create();
ds_queue_enqueue(foo, 1);
ds_queue_enqueue(foo, 2);

bar=ds_queue_create();
ds_queue_enqueue(bar, 3);
ds_queue_enqueue(bar, 1);
ds_queue_enqueue(bar, 2);
ds_queue_dequeue(bar);

return(equality_test(foo, bar));

```

should return `true`

Options I know of:

* `foo == bar` returns `false`, presumably because it's checking whether they point to the same queue as opposed to having the same values.
* `ds_queue_write(foo) == ds_queue_write(bar)` seems to be sensitive to the queues' histories. If I just enqueue `[1,2]` on each queue, it gives `true`. But because I added and then dequeued an irrelevant value on `bar`, the serialized strings differ even though the current values are identical.
* Iterating through the items one at a time and checking equality works for arrays, but doing this using `ds_queue_dequeue` destroys the queues. Is there a nondestructive way to read elements of a queue, other than the head and tail?
* Per liggiorgio's comment below, I could duplicate the queues with `ds_queue_copy` and destructively iterate over the duplicates -- is this the best way?

As far as I know the same issues apply to stacks.

# Answer
Your third approach is just fine, apart from being 'destructive' towards original data. But you can easily copy and clone the data to separate structures, and use these instead to check equality among values.

You may want to use simple `ds_list`s and take advantage of the function `ds_list_find_value()` to search for L1's values in L2's.
> 1 votes

---
Tags: game-maker
---


title: Complex layout in Unity

text:
# Question
Title: Complex layout in Unity
I need ScrollRect, but at startup I don't know how many elements it should keep. Moreover this elements should be kept in categories that can fold/unfold.

The problem is that height of `content` doesn't updates after folding/unfolding. This worked in Unity 5 with ContentSizeFitter in `content` and each category, but this doesn't work with Unity 2017.

Items are added at runtime with instantiating from prefab in a certain category.

Is there any solutions without additional scripting?

**EDIT**

Additional screenshots  When unfolded can't scroll anything because `content` size is too small

This is script part for instantiating items inside categories.

# Answer
> 1 votes
"Children should also have a `ContentSizeFitter` to change their height in order for parent `ContentSizeFitter` to change its height." - that was my mistake. It's not true that children should have it. What is important is that `ContentSizeFitter` \- doesn't have a clue what behaviour it should use to fit all the content. For example, you have multiple child elements with `width: 100` and `height: 50`, you have `3` of them. They are all placed in content that has `ContentSizeFitter` on it. While you would expect `ContentSizeFitter` to add all the bounding boxes and calculate it's own bounding box it doesn't do that.

**Why?** \- Because it needs some kind of trigger that will define it's behaviour.

**And what can serve as this trigger?** \- Layout components.

`LayoutGroup` component tells `ContentSizeFitter` that it has this width and this height or (it depends on internal implementation) `ContentSizeFitter` gets width and height from some `Layout Group` that calculates those bounds. It's worth a try to create a custom `LayoutGroup` component that calculates bounds as required for your project. But in most cases `Grid`, `Vertical` and `Horizontal` are enough to achieve the desired results.

If native component doesn't work as required then you may as well write your own, or extend the behaviour of a current one.

Here is an example of how additional functionality can be added to the component:

```
[AddComponentMenu("Layout/Advanced Content Size Fitter", 141)]
[ExecuteInEditMode]
public class AdvancedContentSizeFitter : ContentSizeFitter
{
    protected RectTransform m_rectTransfrom;

    [SerializeField] protected Vector2 m_minSize = new Vector2(0f, 0f);
    [SerializeField] protected Vector2 m_maxSize = new Vector2(250f, 250f);

    protected override void OnRectTransformDimensionsChange()
    {
        base.OnRectTransformDimensionsChange();

        if (this.m_rectTransfrom == null)
            this.m_rectTransfrom = this.transform as RectTransform;

        this.m_rectTransfrom.sizeDelta = new Vector2(Mathf.Clamp(this.m_rectTransfrom.sizeDelta.x, this.m_minSize.x, this.m_maxSize.x), Mathf.Clamp(this.m_rectTransfrom.sizeDelta.y, this.m_minSize.y, this.m_maxSize.y));
    }

    protected override void OnEnable()
    {
        base.OnEnable();

        this.m_rectTransfrom = this.transform as RectTransform;
    }
}

```

This one basically adds min, max size to the component behaviour while keeping the previous behaviour.

---
Tags: unity, gui
---


title: How to make low poly ground look better

text:
# Question
Title: How to make low poly ground look better
I'm working in Unity and have created some low poly meshes using blender. Currently, the meshes look good, but the ground seems very lacking. I am not sure how to make it feel natural or even look good in general.

Here is a current image

The ground needs to remain mostly flat due to the game placing flat objects on the top of the plane and the image shows the exact camera angle we are using. But, as you can see in the image, the ground is extremely lacking and it doesn't look like a ground but instead just a flat background color. I've tried textures but it does not look good with the trees and low poly design.

How can I make the ground look better?

# Answer
> 6 votes
A texture is a simple idea. You say you've tried some and they didn't look good. If you created the texture out of polygons would it look better?

Or better yet, maybe try making the ground a flat plane made out of triangles, but vary the color of the triangles. Either use shades of green, or have both green and brown for grass and dirt, maybe white for snow if appropriate.

Another idea is make the ground just barely not flat so that you don't have to change your physics but the light hits each poly of the ground just slightly differently to give you a different feel.

---
Tags: 3d-meshes, art, world-design, low-poly
---


# Question
Title: How do I move an object in a square pattern?
I have some bots that can move via setting the x and y. I have already been able to make them move in a circle pattern, but how do I make them rotate around the player in a square pattern? I'm not very good at math, so I'd appreciate some help.

Here is what it looks like now:

here is how I did circle pattern.

```
var PI2 = 2 * Math.PI, FOLLOWADD = PI2 / 18/*PI2 / 360 * 20*/, BOTSLICE = PI2 / BOTS;

bots.follow = function(id) {
    if (!ppl()[id])
        id = protocol.id; //player is default

    var pos = getPos(id), a, i = BOTS;
    while (i--)
        if (this[i] && !this.busy) {
            a = BOTSLICE * i + f;
          this[i].pos.x = pos.x + (Math.cos(2 * Math.PI / BOTS * i + f) * 3);
            this[i].pos.y = pos.y + (Math.sin(2 * Math.PI / BOTS * i + f) * 3);
        }
    f = (f + FOLLOWADD) % PI2;
}.bind(bots);

```

# Answer
> 1 votes
To keep the code similar, the bots could move around a larger circle which is then bounded in X and Y. The result would be a square inscribed in a circle:

The radius of the circle is the distance from the centre of the square to a diagonal corner. This can be calculated by Pythagorean theorem:

$$radius = 0.5\times\sqrt(width^2+height^2)$$

For our example 50x50 boundary,

$$radius = 0.5\times\sqrt(50^2+50^2)$$ $$radius = 35.355$$

Once the radius has been calculated, the value can be inserted into the existing code. Then there are four lines to bound X and Y into min and max zones:

```
this[i].pos.x = pos.x + (Math.cos( ((2 * Math.PI) / (BOTS * i)) + f) * 35.355);
this[i].pos.y = pos.y + (Math.sin( ((2 * Math.PI) / (BOTS * i)) + f) * 35.355);

this[i].pos.x = Math.min( this[i].pos.x , pos.x + 25);
this[i].pos.x = Math.max( this[i].pos.x , pos.x - 25);
this[i].pos.y = Math.min( this[i].pos.y , pos.y + 25);
this[i].pos.y = Math.max( this[i].pos.y , pos.y - 25);

```

The 50x50 pixel boundary has been hard-coded here, but the 35.355 and 25 could be moved into variables.

---
Tags: mathematics, javascript
---


# Question
Title: Why does my collider rotate correctly on a slope only when a ray is cast directly from its center?
Edit: This answer might also be helpful to those who come across this question.

I've been messing around with raycast collisions and slopes, but am having an issue when trying to get my collider to stay grounded and rotate to the angle of a slope. Everything works when I cast a ray from the exact center of my collider, but things mess up when I try to cast rays from another point along the horizontal center of the collider.

For example, let's say my character's position is (0,0), and the "center" ray has an origin at (0,0). This gives me the behavior I want, but if I try to cast a ray from (-0.5, 0) my character is no longer flush with the ground even though the center.y point is the same. Oddly enough, this discrepancy only manifests when the character is on a slope; if it's on a flat surface the behavior of both origin points is the same.

Here's the correct behavior using the center ray:

Here's a similar ray which is supposedly being cast from the center.y (the origin is `Vector2(bounds.max.x, bounds.center.y)` of my collider), but with incorrect behavior:

...but that same ray works fine on a flat surface:

Even though Unity's `print()` function tells me the origin point.y of both rays are the same, I suspect that this must not be true based on how the ray is being drawn by `Debug.DrawRay()`, and from simply testing things in the game view. My script is fairly simple:

```
using UnityEngine;

public class RayRotationTest : MonoBehaviour
{
    //Movement values to tweak in the inspector
    public float gravity = -20;
    public float speed = 5, jump = 5;
    public LayerMask collisionMask;

    private BoxCollider2D boxCollider;

    private Vector2 velocity;
    private bool below;

    //The different origin points of the ray
    private Vector2 center, centerRight, centerLeft;

    private void Awake()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    private void LateUpdate()
    {
        velocity.y += gravity * Time.deltaTime;
        MoveCharacter(velocity * Time.deltaTime);
    }

    //Get the bounds of the box collider, and set the ray origin points accordingly
    private void UpdateRaycastOrigins()
    {
        Bounds bounds = boxCollider.bounds;

        center = new Vector2(bounds.center.x, bounds.center.y);
        centerLeft = new Vector2(bounds.min.x, bounds.center.y);
        centerRight = new Vector2(bounds.max.x, bounds.center.y);
    }

    private void MoveCharacter(Vector2 velocity)
    {
        UpdateRaycastOrigins();

        bool wasGrounded = below;
        below = false; //Reset state

        CollideVertically(ref velocity, wasGrounded);
        transform.Translate(velocity);
    }

    private void CollideVertically(ref Vector2 deltaMovement, bool wasGrounded)
    {
        float directionY = Mathf.Sign(deltaMovement.y);
        float rayLength = (wasGrounded) ? 5 : Mathf.Abs(deltaMovement.y) + boxCollider.size.y * .5f;

        Vector2 rayOrigin = (Mathf.Sign(deltaMovement.x) == -1) ? centerLeft : centerRight;
        rayOrigin.x += deltaMovement.x;

        //Unity says the y coordinates of both of these points are the same
        print(center);
        print(centerRight);

        RaycastHit2D hit = Physics2D.Raycast(rayOrigin, transform.up * directionY, rayLength, collisionMask);
        Debug.DrawRay(rayOrigin, transform.up * directionY * rayLength, Color.red);

        if (hit)
        {
            float collisionAngle = Vector2.Angle(hit.normal, Vector2.up);
            float currentRotation = transform.eulerAngles.z;
            transform.rotation = Quaternion.Euler(new Vector3(0, 0, collisionAngle));

            deltaMovement.y = (hit.distance - boxCollider.size.y * .5f) * directionY;
            velocity.y = 0; //This stops the character from accumulating gravity when grounded
            below = true;
        }
    }
}

```

Essentially, I'm casting a ray from the center of the collider down to the ground, making sure its direction matches the direction of the y axis when the collider is rotated; this is done by setting the ray direction to `transform.up`. If it hits something I set my change in movement this frame, `deltaMovement.y`, to be the distance away from the origin point of the ray, subtracting half of my box collider's size to make sure I'm flat on the ground. I don't understand why the formula `deltaMovement.y = (hit.distance - boxCollider.size.y * .5f) * directionY` works in all cases except for the case shown in the last image.

Surely I must be missing something having to do with the ray's origin point. I think I really just need to know how to change `deltaMovement.y = (hit.distance - boxCollider.size.y *.5f)` to fix this problem, but I'm not sure what to do.

# Answer
> 2 votes
`bounds` is an axis-aligned bounding box that looks like this:

Instead of using `bounds` (which are in world coordinates) to calculate your ray's origin, use the local position, `Vector.right/left` and an appropriate scalar value, and then transform to world coordinates:

```
var scalar = 0.5f;
center = transform.TransformPoint(transform.localPosition);
centerLeft = transform.TransformPoint(transform.localPosition + Vector2.left * scalar);
centerRight = transform.TransformPoint(transform.localPosition + Vector2.right * scalar);

```

---
Tags: unity, collision-detection, rotation, raycasting
---


# Question
Title: Is there a name for assets in a video game which allude to a depth they don't have?
A very particular question, hoping it's not too out of place here: is there a name within video game development for assets in a game that allude to a depth they don't have? Without knowing enough about video games to use the proper vocabulary, I'm thinking of houses which are hollow inside, distant landscape which you can't reach (and doesn't truly extend as far as it implies), etc.

# Answer
> 2 votes
As in other creative industries (film, literature) they're usually just referred to as *visual cues* to differentiate them from active entities or geometry.

As an aside: Unless you were intended to see inside it, such a house wouldn't be hollow inside, rather it would *have no absolutely interior at all*, potentially saving on processing cost.

# Answer
> 2 votes
In Hollywood these kinds of sets are called **Facades**.

In real life you can see something similar in the American Old West towns where buildings would have a large roofline from the front, but the entire rest of the building is squat and utilitarian; the front is a Facade to put a pretty face on the reality.

On TV shows almost all the interior shots are in an open studio with nothing but walls rolled around on wheels.

Note that these are not **Imposters** meant to stand in the the real thing, these are outright fakes and there is no real thing. If you can transition to the a real space at some point than Imposter would be the term.

---
Tags: assets, terminology
---


title: What does SoC stand for?

text:
# Question
Title: What does SoC stand for?
… and no, I do not mean System-on-a-Chip.

I stumbled upon this question which was using the acronym in the context of graphics, and found myself wondering about its meaning. Neither the question nor the answer further explained the acronym, and a search on google only got me "system-on-a-chip", which I was already familiar with, and "security operations center", which I was less familiar with.

What does SoC stand for in the context of game development (and/or software engineering)?

# Answer
> 48 votes
It stands for Separation of Concerns, i.e. designing a software so that each section has a specific purpose.

As you guessed, it's a general software engineer priciple and it is not specific to game design/programming.

This is often done (and not limited to) to reduce the coupling between sections, resulting in better reusability, code clarity and (sometimes) teamwork.

---
Tags: terminology
---


# Question
Title: How can I cleanly separate the UI from the game logic in my Cocos2d game?
I've been working on a little game for the last few months, trying to approach it as a software engineer and employ best patterns and practices in my coding. I have gotten to the point where I have to distinct elements in my game.

1. The Game Logic: aka business logic. Its the meat of the game rules. It contains all information about game objects (such as Character, Weapon, and Item class definitions). It contains the game world as far as rules are required; mainly so Characters are aware of the world they are in, and who else is in it. It contains a chunk of logic use to determine how Fighting is resolved between Characters, as we as other game actions requiring rules. It contains my AI implementations. So in reality it's a combination of Class definitions and Service logic.

As it stands, the Game Logic can actually play out a game without any interface. All I need to do is create a World, add some Characters to it, assign some AI's to them, then in a loop tell their AIs to run. The result of each AIs action is reflected in the states of the Characters (eg, if damaged, health is reduced), and a summary of what happened is returned by the execution (which is intended for the UI to make sense of what happened).
2. The Game UI: which is using Cocos2d-xna for WP7. It contains definitions of all the different animations. It takes in inputs and sends the to the Game Logic, and renders its results.

As it stands, as well as all UI components for a Character (textures, sprites, animations) a UI Character also contains a Begin method which executes a Cocos2d Sequence (ccSequence) to do two things 1) Execute AI and render result for this Character 2) Re-Execute the sequence (essentially its own call back loop for executing actions).

The problem I keep running into is, the more I try to keep these two layers separate, the more they need to come together. E.g., my UI Character which is used to render what the Game Logic character is doing, so it needs a reference to the Character object from Game Logic. When this Character's AI attacks someone in the Game Logic world, the UI needs to know what happened. This works fine for rendering its own Animations based of its results, but to know what to do for other Characters affected by this action is difficult as I dont have reference to them. At the moment I do this by queuing up Pending Animations in the other character's Game Logic Character and render it when that character next executes, but this is anti SoC (*Separation of Concerns*) as it now contains something specific for the UI to focus on.

I don't want the two projects to merge into one where a Game Logic Character contains all things UI as well, such as animations and actions. Is there a nice clean way that is used for this separation? Ideally something that works nicely with Cocos2d's Action pattern?

# Answer
I agree with Engineer's answer, where the main point is "*don't fight the framework*".

# Games are different

However, another point I want to add is that when it comes to software, **games are different**.

Even though the article is a bit outdated by now, I want to quote a part from Joel's five worlds of software programming:

> Here’s an important thing to know. Whenever you read one of those books about programming methodologies written by a full time software development guru/consultant, you can rest assured that they are talking about internal, corporate software development. Not shrinkwrapped software, not embedded software, and certainly not games. Why? Because corporations are the people who hire these gurus. They’re paying the bill. (Trust me, id software is not about to hire Ed Yourdon to talk about structured analysis.)

**All that clever architecture stuff like MVC, onion architecture etc, is not made for games.**

# Have an anecdote

I struggled for about half a year to develop a layered approach to writing a game in Unity3D, until I finally thought good and well about a thing as simple as *movement*.

You probably want to put some kind of normalizing code in between input and actually moving your game elements - but **passing a Vector2 down 3 layers, only to do some super simple math with it and then passing it up 3 layers again is just over-engineered**. Especially if you just quickly wanted to try it and might scrap it again in a week, *as is common when developing games*.

# Business rules

Another problem is that what is called "business rules" *in corporate software* is just very difficult to differentiate from the rest *in a game*. For example, look at collisions: If two boxes collide, it would be a business rule that they move in a certain way after that - but **you don't want to write a whole physics engine in your business layer.** You just want to create a box and then let the physics engine handle it.

# Have another anecdote

Now, here's the thing: At my workplace, we also use Unity3D. Not for making a game, but some architecture stuff. We mostly just use the engine as a 3D renderer (plus the physics engine for a few raycasts etc). I managed to get it working with a *Clean Architecture* approach. It wasn't *too* easy, but I am now reaping the benefits from that. There's no ongoing real-time processes. It's mostly the user clicking buttons in the GUI and then something happens in the virtual world and *for that, it works.* I did that *before* I failed trying to create a game this way - so it's not an experience thing.

**It's not really the game-ness that makes the difference, but the real-time-ness of things colliding and spawning and raycasting etc.** If you make a management game which is really just clicking buttons in the UI, those corporate architectures will work just fine (but will still take some tinkering to play nice with game engines).

# We can still *separate concerns*

With all that being said, concerns can still be separated - it just doesn't work in the same way as corporate software. The arguably most established way to separate concerns in games are Entity-Component-Systems. Here, rendering is the concern of the renderer component and playing audio is the concern of the audio component, but these components don't care about each other.

As it happens, that is exactly what Cocos2D gives you.

So, going a full circle towards the beginning of this answer, "*don't fight the framework*", but **if you want your concerns separated, Cocos2D gives you a way to do that, *which will play nice with the rest of it*.**
> 3 votes

# Answer
If you want decent SoC for games, without annoying wrapper code and consequent performance concerns, you should to pick a language / platform / library combination that meets that goal in the first place, or at least gives you the ability to write your own framework without undue restrictions.

You'll soon enough get the Cocos2D guys telling you to do it the Cocos2D way. **And I'd agree with them.** There is no inherent MVC separation there, and trying to force it will make your life harder.

(I maintain a small, cross-platform library on google code which exists for the purpose of cross-platform SoC. I wrote it in such a way as to make it repluggable between languages / platforms, but some are just too far gone to bother with. Take Unity3D for instance. The core classes / "framework" that they have in place is so obtrusive and over-engineered that while I certainly could wrap Unity3D, I'd probably not even attempt the task in the first place -- not to mention that wherever an accepted framework already exists, the associated community could probably be said to hold fairly rigid beliefs about how awesomely structured it is, and so tend not to want to adapt to a whole different structure. Hence the above comment about the Cocos2D guys. They have a point, even if the architecture they're willing to use, is not particularly well thought out.)

But this is about *your* coding comfort, not anyone else's. So for decent architecture, my advice is look into rolling your own in a more flexible, less assumptive language / platform like JS, Python, Java, C or C++.

Adapt, or move on.
> 1 votes

---
Tags: xna, game-design, architecture, cocos2d
---


title: When should I make different LODs?

text:
# Question
Title: When should I make different LODs?
This is something I have been discussing with my team as to how we should approach it on our project.

The question is, what is better practice, make your model already with different Levels of detail, importing everything in one go, or importing the base model on the game and only then making LODs for it later?

# Answer
Different LOD levels are only useful for your game when two conditions are true:

1. You show the objects from many different distances, so the different LOD levels will actually be used in practice.
2. You have so many objects on the screen at once that the rendering performance becomes too bad for your target platform if all models are maximum-detail.

Unless you **know** that these will be the case, then starting out with creating several LODs for each model might turn out to be premature optimization. When your game isn't actually that graphically ambitious, then you might discover that your game still runs at steady 120FPS even when you use the maximum detail models. Then all the time your 3d artists spent on creating and updating simplified versions will be time wasted they could have spent on improving the high detail models or creating more content.

However, in one game I made the low-LOD models were a by-product of my workflow. I wanted a playable prototype ASAP, so I created very simple, untextured models of the most important entities. When I then started to polish the game, I created high-detail versions of these models, but I kept the initial low-detail prototypes around as low-LOD models.
> 2 votes

# Answer
Depends on the game I'd say. If you make something like Spyro, where objects can come close to the screen or far away quite quickly, then you'd want to have them all loaded at the same time. The whole point of LODs is to make the game run faster, so wasting CPU to load new LODs defeats the purpose.

However, if the purpose is something like a character selection screen, I've seen games, where all characters are in low quality, and once you click one of them, it starts loading an HD version, which doesn't sound unreasonable. Dead or Alive does something similar, but it has a 2D image, and loads the 3D model when you select the character. It's not unreasonable to do the same with different LODs on 3D.
> 1 votes

---
Tags: level-of-detail, modelling-techniques
---


# Question
Title: How to implement smooth wandering on an annulus?
I am creating a 2D action platformer and want to create some steering behavior for a mage enemy.

Basically, I want the mage to smoothly wander inside an annulus centered on my player.

Below is an image depicting an example path the mage could follow.

The enemy currently has simple seek behavior. It simply accelerates toward whatever is set as its target.

I tried choosing a random target point in the annulus every so often, but when you do this, the enemy sometimes drifts across the center of the annulus to reach a point chosen on the other side.

So my question is, how can I achieve the desired movement?

# Answer
If you are using steering behaviors to guide your objects, you could add a repellant force in the center of the circle.

A repellant force is a vector that points in the direction from the center of the circle to the object. The length of the vector is in inverse relation to the distance of the object from the cente (closer: bigger force, distant near zero force). You can tweak the repellant strength to suit your needs.

If you add this force to your steering behaviors and your object will avoid the center and move nicely around your character.
> 2 votes

# Answer
Give your mage a movement direction vector. When mage moves, turn it around slowly - this will give you wiggling movement. If mage goes outside of allowed range, or gets close to it, turn direction vector towards the center. If it gets too close, turn it away from center. Depending on how fast and how often you change direction vector, you may get the loops like on your image.
> 2 votes

# Answer
First let me preface this by saying, I think there's a better way to approach this problem by using a different metric (i.e. something like using polar coordinates rather than euclidean X,Y coordinates).

That said, using standard X,Y coords, the easiest way I can see to approach this problem is a test and reject pattern:

1. Randomly generate a potential new destination (see note below about this step)
2. Test if the line between the current position and the current destination under consideration clips the center circle. If so, reject the current point & go back to step 1.
3. Otherwise the current destination is valid & should be used as the next random heading.

While easy to implement, test and reject strategies should always be throughly vetted before use. They don't always work well in situations where you need an immense amount of solutions (i.e. trying to solve multiple instances of the problem repeatedly in real time) or in situations with lots of constraints (i.e. avoiding other obstacles, maintaining line of sight on enemies, etc). That said, they often give answers that are good enough, quickly enough to allow you to focus on the more interesting parts of the game, so don't be too put ooff by the potential ineffiecency.

Regarding the generation of random points: beware of simply picking a random angle & distance, as this will result in a bias towards points near the center. The solution to this problem is to take the square root of the radius which will skew the selection back to a uniform distribution.
> 2 votes

---
Tags: movement, steering-behaviors
---


title: Transform inputs don't work

text:
# Question
Title: Transform inputs don't work
I'm writing a C# player script for a class and when I run, the sound inputs work fine, but the movement inputs don't respond, and I don't know how to fix it.

Code:

```
Rigidbody rigidbody;
AudioSource audioSource;

void Start(){
    rigidbody = GetComponent<Rigidbody>();
    audioSource = GetComponent<AudioSource>();
}

void Update(){
    ProcessInputs();
}
private void ProcessInputs()
{

    if (Input.GetKey(KeyCode.Space))
    {
        rigidbody.AddRelativeForce(Vector3.up);
        if (!audioSource.isPlaying)
        {
            audioSource.Play();
        }
    }
    else
    {
        audioSource.Stop();
    }
    if (Input.GetKey(KeyCode.A))
    {
        transform.Rotate(Vector3.forward);
    }
    if (Input.GetKey(KeyCode.D))
    {
        transform.Rotate(-Vector3.forward);
    }
}

```

# Answer
> 0 votes
You have to multiply your vectors by a certain value. This value could represent a speed, distance, amount, or force.

So for example,

```
rigidbody.AddRelativeForce(Vector3.up);

```

would be

```
 rigidbody.AddRelativeForce(Vector3.up * 5);

```

and

```
transform.Rotate(Vector3.forward);

```

would be

```
transform.Rotate(Vector3.forward * 10);

```

---
Tags: unity, c#, input
---


# Question
Title: Did retro pixel artists design with CRT's in mind?
There is an often stated claim on discussion boards like Reddit that now retro games of the 8 bit and 16 bit era actually had their art designed with CRT's in mind. I am not talking about video modes or video signals or hardware limitations as a lot of games supported multiple options. I am talking about the final output on the physical device that you observed with your eyes. Did artists really make conscious changes to their art because of this ? (eg. draw the edges of a sprite differently to appear less aliased in a given display)

# Answer
Yes they did. That is, expert pixel artists on some systems were able to pull this off.

Some of the pixel artists used dither patterns to change the hue of an object and create gradients.

Note to leverage the effect, the system had to have a palette and resolution to create such effects. The Atari 2600 pixels were too big and the palette to limited to use these techniques. This was first employed in coin-operated arcade titles. Later with more sophisticated monitors, capable of resolutions above 640x480 this technique became obsolete due to the fact that color bleeding pixels simply became a thing of the past- even on CRT displays.

There is an example of a car in a top down racer (I couldn't find the image) where the car has a strange pattern of green and red pixels when viewed on a LCD screen. When viewed on a CRT screen the pixels somewhat blended and gave the car a pinkish color which was otherwise not possible with the standard palette of the system.

The image below shows how different a CRT image looks from the sharp pixel one:

With the example cited above; yes some pixel artist leveraged the bleeding of pixels on CRT screens.

Keep in mind though that at the time, the pixel artists *viewed their art on CRT screens* as they were creating them. So they tweaked these things as they went along. Expert artists knew to leverage these effects, good artists simply drew it and it looked good. Then there is the group who created pixel art and weren't aware of these techniques or worked on a system where it was no option.

Added example of DMGregory's comment: This is the waterfall in *Sonic: The Hedgehog 2*, where the CRT bleeding effect is used to create transparancy (something not possible on the Sega Genesis/Megadrive) One can imagine that this technique in the hands of an expert artist provided new options in creating colors and contours.
> 7 votes

---
Tags: pixel-art
---


# Question
Title: How to access Lit shader properties through code?
Currently i'm using HDRP in my project, so i have a question. How can i access Lit shader properties through code ? Or where i can see names of variables in this shader ?

For example:

# Answer
> 1 votes
HDRP is still under heavy development and all the code is still in flux. Even if you find some code that works right now chances are it will stop working very soon. That's why there aren't really any tutorials/etc for HDRP code yet. Really, the safest shader method right now is to use Shader Graph.

But... you can find the source code for all the SRP/Shader Graph stuff here. The particular variable you highlight in your screenshot is called \_BaseColorMap for the texture part and \_BaseColor for the color part. Where those variables are used depends on the rendering path you have selected and which features you have enabled in the shader.

Once the code stabilizes it will be easier to point to specific bits of code to show what does what. I'm looking forward to that myself.

(Answer by Jick87 on Unity3D forum)

---
Tags: unity, shaders, graphics
---


# Question
Title: How to Implement a Very Simple Game State Manager in Unity?
I’ve tried a bunch of different implementations, and trawled everything online I could get my hands on. Everything has downsides, nothing plays nicely with how Unity wants you to work.

Let’s keep it simple. You want to track in-game time. You want this to be available as a ScriptableObject. You need a MonoBehaviour to keep the time updated. You want to ensure there’s just one such GameState ScriptableObject and one such GameStateManager MonoBehaviour. You don’t want to manually add the manager to all scenes.

Is there a standard and sane way to achieve this without resorting to black magic?

---

To keep this grounded, here’s the boilerplate ScriptableObject:

```
    [CreateAssetMenu(fileName = "GameState", menuName = "ScriptableObjects/GameState")]
    public class GameState : ScriptableObject {

        /// <summary>
        /// The time passed in game, in game time, in seconds.
        /// </summary>
        public float TimePassed { get; private set; } = 0.0f;

        /// <summary>
        /// Moves the in-game time and date forward.
        /// </summary>
        /// <param name="addedGameTime">Time to add, in in-game seconds.</param>
        public void MoveTimeForward(float addedGameTime) {
            // Move the time passed forward
            TimePassed += addedGameTime;
        }

    }

```

And MonoBehaviour:

```
    public class GameStateManager : MonoBehaviour {

    /// <summary>
    /// The state of the game.
    /// </summary>
    public GameState gameState;

    // Start is called before the first frame update
    void Start() {
        // If we use a Singleton, and not drag a reference using the editor:
        gameState = GameState.Instace;
        // Mark that this should not to be destroyed when loading new scenes
        DontDestroyOnLoad(gameObject);
    }

    // Update is called once per frame
    void Update() {
        // Update the in-game time
        gameState.MoveTimeForward(Time.deltaTime);
    }

}

```

# Answer
> 5 votes
Reload-proof Singleton

There is no way without black magic, but here is that black magic ^\_^:

```
using UnityEngine;
using System.IO;

#if UNITY_EDITOR
using UnityEditor;
#endif

#if UNITY_EDITOR
public static class ScriptableObjectUtility
{
    /// <summary>
    /// This makes it easy to create, name and place unique new ScriptableObject asset files.
    /// </summary>
    public static T CreateAsset<T>(string path, string name) where T : ScriptableObject
    {
        T asset = ScriptableObject.CreateInstance<T>();

        if (path == string.Empty)
        {
            path = "Assets";
        }
        else if (Path.GetExtension(path) != string.Empty)
        {
            path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), string.Empty);
        }

        string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(path, name + ".asset"));

        AssetDatabase.CreateAsset(asset, assetPathAndName);

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        EditorUtility.FocusProjectWindow();
        Selection.activeObject = asset;

        return asset;
    }
}
#endif

```

---

```
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

// Reload-proof Singleton
[CreateAssetMenu(fileName = GameState.DEFAULT_GAME_STATE_NAME, menuName = "Game State", order = 202)]
public class GameState : ScriptableObject
{
    private const string DEFAULT_GAME_STATE_NAME = "Game State";

    public static GameState instance;
    public static GameState Instance
    {
        get { return instance ??
                (instance = Resources.Load<GameState>(GameState.DEFAULT_GAME_STATE_NAME)) ??
                (instance = ScriptableObjectUtility.CreateAsset<GameState>(Path.Combine("Assets", "Resources"), GameState.DEFAULT_GAME_STATE_NAME)); }
    }

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    private static void CreateGameStateManager()
    {
        new GameObject("[Game State Manager]", typeof(GameStateManager));
    }
}

```

---

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameStateManager : MonoBehaviour
{
    private void Awake()
    {
        if (GameState.Instance == null) // Null check is important, it's also a way to initialize and find GameState on Awake to prevent spike during gameplay.
        {
#if UNITY_EDITOR
            Debug.LogError("Game State instance could neither be found nor created.");
#endif
        }
    }
}

```

---

## Just Thoughts

The basic idea behind this is that `ScriptableObject`s preserve data between scenes (if I am not mistaken). So having only 1 instance of `GameState` should keep things in check. It's automatically `lazy` loaded from `Resources` when addressed. `[Game State Manager]` is created before scene load, so it should be first to initialize (but I am not sure, I didn't test it) and is created automatically for every scene and deleted when scene is unloaded. If you load scenes in `Additive` way then you would have to make some manipulations to keep only 1 instance of it for both scenes, I didn't have time to test additive scene loading with it, but it's great approach, I will probably use it in a few months and update my answer to share more info.

Inspired by: Overthrowing the MonoBehaviour tyranny in a glorious ScriptableObject revolution

```
// Old link that doesn't seem to work anymore: https://unity3d.com/learn/tutorials/topics/scripting/overthrowing-monobehaviour-tyranny-glorious-scriptableobject .

```

---
Tags: unity, c#
---


# Question
Title: Stop movement if transform.position.y == 0
Why does the following code not step the object's movement when its y coordinate reaches zero?

```
    public GameObject cube;
    private GameObject inst;
    public float speed=5;

    void Start () {
        inst = Instantiate(cube, new Vector3(0, 10.6f, 0),Quaternion.identity);
    }

    void Update () {

        inst.transform.Translate(speed * Vector3.down * Time.deltaTime, Space.World);

        if (inst.transform.position.y == 0)
        {
            speed = 0; //stop moving
        }
    }

```

# Answer
> 6 votes
Because the Y position is never EXACTLY 0.

Its for example 5.5 next frame: 4.3 next frame: 3.1 next frame: 1.9 next frame: 0.7 next frame: -0.5

change the if to

```
if (inst.transform.position.y <= 0)

```

Then add:

```
inst.transform.position = new Vector3(inst.transform.position.x, 0, inst.transform.position.z);

```

next to:

```
speed = 0;

```

---
Tags: unity, c#, transformation
---


# Question
Title: How to avoid the cutoff of a Sprite when overlapping in a terrain?
I have a scene where I have a terrain as a PlaneGeometry. And I'm trying to locate a building on it as Sprite. But I'm not able to put that building/sprite centered on the terrain without getting a cutoff.

Make sense because the terrain is cutting the half. But I'm just wondering if there is a technique to solve this problem.

I tried to rotate the sprite as a 3D object. But does not have this property. Also tried using a PlaneGeometry with a MeshBasicMaterial, but the result of the Image looks blurry and without transparency.

# Answer
> 0 votes
The best solution I found is adding two scenes, one for the terrain and one for the sprites.

Is important to add two lines after each render()

```
renderer.render(sceneTerrain, camera)
renderer.clearDepth()
renderer.autoClear = false

renderer.render(sceneSprites, camera)
renderer.clearDepth()
renderer.autoClear = false

...

```

# Answer
> 3 votes
You can force the sprite to render always on top by disabling the depth testing in the sprite's material.

```
material = new game.THREE.SpriteMaterial({
  depthTest: false
});

```

---
Tags: sprites, terrain, perspective, three.js
---


# Question
Title: how to set multiple materials using array in the submesh of an object
I'm trying to insert multiple materials into the object's submesh using the array, but I'm not getting

public GameObject\[\] obj;

```
//material mat;

public void Color(Material mat) {

    for (int x = 0; x < obj.Count; x++)
        obj[x].GetComponent<MeshRenderer>().sharedMaterials[1] = mat;

    Material[] mats = GetComponent<Renderer>().materials;
    mats[1] = mat;
    GetComponent<Renderer>().materials = mats;

    {
        print("New Material");
    }
}

```

# Answer
> 1 votes
```
material mat;
GetComponent<MeshRenderer> ().sharedMaterials [1] = mat;
Material[] mats = GetComponent<Renderer>().materials;
mats[1] = mat;
GetComponent<Renderer>().materials = mats;

```

First error: The class "Material" should be in capital letters. (your code shouldnt compile)

Second error:

```
GetComponent<MeshRenderer> ().sharedMaterials [1] = mat;

```

doesnt do anything. You can not assign that material like this.

The rest of your code looks correct.

1. Did you assign the "mat" in the inspector?
2. Does your mesh even have more than 1 submesh?
3. Do you even want to assign more than 1 material?
4. Whats the error ? Doesnt it compile? Null reference? Nothing happenes?
5. Does your mesh renderer get the materials or does it just look wrong in the 3d view?

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MaterialArraySetter : MonoBehaviour {

    public Material Material1;

    void Start ()
    {
        Material[] materialsArray = GetComponent<Renderer>().materials;
        materialsArray[1] = Material1;
        GetComponent<Renderer>().materials = materialsArray;

    }

}

```

EDIT2:

You seem to have compiler errors.

---
Tags: unity, materials
---


# Question
Title: Can Inspector interactions be used with UNET
SyncVar and RPC calls allow a UNET server to send messages to clients, but these messages are not triggered if the server-side change comes from the inspector or a custom editor (and presumably any non-MonoBehaviour).

EG I use the inspector to change a SyncVar - only the server is updated. Or press a CustomEditor button which calls a method marked with Target/ClientRpc - it will just execute that method on the server.

What is the best way to call UNET networking functions from Inspector GUIs and non-MonoBehaviour code?

# Answer
When using a SyncVar, a network change can be triggered by adding a custom Editor with a field of the same type. This editor can then set the syncvar property to match the editor value when it change, which lets network updates trigger as normal.
> 1 votes

---
Tags: unity, unet
---


# Question
Title: Detecting a Collision Between Two Bodies Undergoing Multiple Transformations
I have been searching for an answer to this for a really long time and I have not found any definitive answers as of yet. What I am trying to do is determine if and when two bodies collided between the times `t0` and `t1`. Calculating this is much more straight forward if each body is only either translating or rotating (about center or any point), but when adding multiple transformations on top of each other, things become a bit more messy. I made this animation to illustrate the problem.

As you can see, at times `t0` and `t1` there are no collisions, but between there are multiple collisions occurring.

One way I thought of for tackling this problem was to reduce the size of the time intervals. So, between `t0` and `t1` there would be a total of `n` updates to check for collisions. This works, but the only way I found that I could guarantee no false negatives, i.e. not finding a collision that happened, was to integrate over extremely small time-steps. As you can imagine, this is very costly because it resulted in the tens to hundreds of time-steps per body per update cycle. I am not saying this idea has no merit (it makes calculating the collision response much easier since I know the exact points of contact), but I would need to find a way to calculate the minimum number of time-steps rather than uniformly moving each body forward one unit of distance/rotation until they reach the desired position and orientation.

So, my question is two parts:

1. Is there a better way of determining if and when a collision occurs?
2. If not, is it possible to calculate the minimum number of time-steps?

P.S.

~~I think the maximum translation per time-step can be the shortest distance between any two points in the body. This would not allow it to hop over anything. When it comes to rotation about the center or orbiting a point I do not know how to determine the minimum angle. It probably has to do with the arc length, but what should that maximum distance be?~~

EDIT: this is not right. For a triangle, the base would be the shortest distance between two of its points, but the top could pass through something that is less wide than the triangle base.

# Answer
> 0 votes
There is a method of pixel-perfect collision detection for polygons such as this that involves using the dot-product operation. You essentially get the angle between each vertex of the shape and divide the screen into two sides and determine if the shape overlaps the other shape's "side" for any two vertices, and if so, move the shape outside of the other shape's collision area and a collision is detected.

Here is a short article on the method:

https://onense.wordpress.com/2011/11/04/the-dot-product-is-awesome-adventures-in-collision/

---
Tags: collision-detection, physics, collision-resolution
---


# Question
Title: How can I create a tunnel/parallax/depth effect based on mobile device tilting?
I would like to create applications similar to what's displayed in these videos:

These mobile application are supposed to react to tilting of the phone, so I created a few 3D objects for this purpose in Blender (one similar shape - 2nd link), but I do not know how to move the back of this object in Unity because I am a beginner.

Can you give me some tips on how to figure this out? I’m not talking about a ready solution or something, I just do not know how to ask a specific question and I do not know what to do next.

# Answer
You would need to investigate how to interact with the phone's gyroscope.

https://docs.unity3d.com/ScriptReference/Gyroscope.html

You could have a camera locked in place pointing originally at a plane in the distance that represents the black box at the end of the tunnel and have textured planes on each side representing the grid. Then use the gyroscope readings to transform the position of the plane at the end of the tunnel (obviously you can't have it transform too far or you'll get wacky results, so the end of the tunnel needs to be bound within a certain range).

I'm not a Unity developer, but based on the few times I've played around in Unity, that would be my best guess as to how to implement it. The cubes flying towards the end of the tunnel are the easy part.
> 1 votes

---
Tags: unity, 3d
---


# Question
Title: A* Pathfinding Finding One of Many Goals
I have my A\* pathfinding algorithm right now working such that given a graph it can find the route from one starting node to one goal node.

This works well for many problems, but sometimes I find that multiple goal nodes are valid.

For example, in a game, an NPC might have to go to a switch to shut a door. If there are multiple switches that shut the door in question, it doesn't matter which switch it goes to - it just needs to go to one of them.

How can I augment my pathfinding algorithm to find the path to the best goal (the shortest path)? As in, the algorithm searches for multiple goals and when it finds just one, it returns the path to that one.

One solution would be to run the algorithm as many times as there are valid goals, but you can guess why that might be inefficient.

# Answer
There are just two changes you need to make to your A\* implementation to handle pathfinding to multiple goals / multiple destinations:

1. When expanding a node, instead of evaluating `if(currentNode == goalNode)` to decide whether to terminate your search, you instead evaluate a predicate using that node as input: `if(IsGoal(currentNode))`

This lets you implement a completely arbitrary logic in your `IsGoal()` predicate - including checking whether the node is one of several available goals, or meets some implicitly defined goal criterion like "this node is a cover location AND it is not in line of sight of an enemy AND it is within 10 m of a healing pickup AND the agent walked an even number of steps to reach it"
2. Modify your heuristic function to estimate the distance to the closest goal. This is the toughest part, but it's reasonably forgiving to get it wrong.

As long as you never overestimate the distance, the algorithm will still return the correct result, so `Heuristic(Node node) { return 0f; }` is safe (this effectively falls back on Dijkstra's algorithm, exploring in all directions equally until a goal is found)

The closer you can estimate the true distance, the more accurately A\* will chase the most promising paths, and skip over redundant exploration of nodes away from the goals.

A sample heuristic for a small number of goal tiles would be:

```
float Heuristic(Node node, Position[] goals) {
      float closest = float.PositiveInfinity();
      foreach(var goal in goals) {
          float distanceSquared = (node.position - goal).squareMagnitude;
          closest = Min(closest, distanceSquared);
      }
      return Sqrt(closest);
    }
```

For a larger number of goals, you may want to use a spatial partition to reduce redundant computation, or pre-compute some heuristic estimates for regions of your map.
> 6 votes

---
Tags: path-finding
---


# Question
Title: How How can I make a simple combo combat system in Unity
I'v been trying to make a melee combo combat system in the Unity Animator, but I can't seem to get it right. I'm trying to go for a combo system that flows from Hit 1 to Hit 2 to Hit 3, ect, with clicks from my mouse, and if I don't click again it will go back to Idle. How would I go about making this combo attack system in the Animator with Unity and C#.

# Answer
> 2 votes
If you're looking for a way to do this directly through Mecanim, it's also possible that way. I'm assuming you're using a trigger or bool parameter to start your transition from idle to attack, although the general principle works regardless. The nice thing about trigger parameters, of course, being that they are set to false automatically once they are used for a transition.

If you have the nodes 'Hit1', 'Hit2' and 'Hit3', and the idle node 'Idle', you can add the transitions: Idle-\>Hit1 Hit1-\>Hit2 Hit2-\>Hit3 all with the condition that the attack trigger parameter is true. Then, add transitions from each hit node back to idle, that are unconditional and occur at the end of the animation.

Therefore, if the player clicks again mid-swing, the state will transition to the next swing, but if the animation ends and they have not clicked, it will transition back to idle and end the combo.

More complex combo trees and patterns can be created in a similar way, with all of the attack nodes transitioning back to idle, but with greater nuance in the transitions between attack nodes.

The primary downside of this is that it becomes more difficult to assign different behavior or damage values to different combos. For that I recommend using AnimatorStateInfo.shortNameHash to detect what state the animator is in and whether that state is a special swing state that, say, deals extra knockback.

# Answer
> 1 votes
There are a ton of ways to build a Combo system in Unity with its Animator system (regardless of if you're using the Mecanim or the Generic Animations).

While there might be a "best way", I suggest you start by breaking down how you want your combo system to work, gameplay-wise. You need a clear view of what kind of restrictions, inputs, timing is required for your combo system even before you start typing the first character in your code.

For example, if you want the player to just hold the attack button and it automatically do Hit1\>Hit2\>Hit3\>repeat until he/she release the button, you can set it up with a simple boolean (bool) that gets true if the Button is down (KeyDown or ButtonDown when pressed, and KeyUp or ButtonUp when released. Avoid making it bool = KeyDown or ButtonDown directly as it might return false negative for 1-2 frame at random time, especially if it involved online stuff.) By setting up a transition from all Hit1, Hit2 and Hit3 where it transition from that to the Idle animation (or Exit) if the boolean is false, it allows the player to do a combo that can stop at Hit2 or Hit3 or even just Hit1. It also allows a sort of "safeguard" against input issues as even if the player release the attack button, he/she can resume the combo by pressing it again before the current attack ends.

If you want the player to release and press the button again, you can do it by either using a timer through some coroutines or directly through a combo manager that gets call from some Event Triggers set directly in the animations. Both has their pros and cons. The Coroutines is stable and precise, but requires you to store, in some ways, all the timing related to the attacks unless all your attacks has the same timing. The Event Trigger set in the animations allows a precise and easy-to-setup way of managing the timing since you place the Event directly into the animation itself. The cons to that is when the game FPS slows down or raise which might affect the timing and feel like lagging input to the player.

Ever since Unity 4.x, the Event Trigger system in the animations don't skip anymore. (In Unity 3.x and prior version, a drop in FPS could make the engine miss an event.) So, there's no risk of having Trigger being skipped if the FPS drops within the player's client. With that said, it can actually drop the FPS itself since the Event "must" be called so it can hang up in-between frames a tiny bit if you're doing a ton of stuff within it. It would be good if you only use Event Trigger to "check" up on things that are analysed in a more mainstream script outside of it. (In other words, having another script that does all the checks/analyses and the Event Trigger only call up on the results from that other script.)

# Answer
> 0 votes
You can use coroutines to achieve this or check the timing.

For simplicity, I will activate animations as a trigger animation. `this._animator.SetTrigger(this._animationHashCodesContainer[(int)this._nextComboAttack])`

**NOTE: I haven't tested this code, it may contain some errors or missing details, it's only to give an idea of implementation. Though, you are free to use it ofc.**

```
public class Character : MonoBehaviour
{
    // You can use array of sting instead of enum (It's not the most scalable solution to use enum but it's faster (maybe it's a micro optimization in this case))
    public enum AttackComboTypes { Slash, Dash, FlyingAttack }
    private AttackComboTypes _nextComboAttack;

    private Dictionary<int, int> _animationHashCodesContainer;

    // or

    [SerializeField] private string[] _attackComboAnimationNames;
    private int _nextComboAttackIndex;

    private Dictionary<string, int> _animationNamesHashCodesContainer;

    private Animator _animator;

    protected virtual void Awake()
    {
        this._animator = this.GetComponent<Animator>();

        this._animationHashCodesContainer.Add((int)AttackComboTypes.Slash, Animator.StringToHash(AttackComboTypes.Slash.ToString()));
        this._animationHashCodesContainer.Add((int)AttackComboTypes.Dash, Animator.StringToHash(AttackComboTypes.Dash.ToString()));
        this._animationHashCodesContainer.Add((int)AttackComboTypes.FlyingAttack, Animator.StringToHash(AttackComboTypes.FlyingAttack.ToString()));

        // or

        for (int i = 0; i < this._attackComboAnimationNames.Length; i++)
        {
            // Don't actually know if this helps to gain more performance in case you need to get hash code from string anyway
            // It's probably useless to use dictionary in this case
            // So I will continue just passing the name of the animation to trigger
            this._animationNamesHashCodesContainer.Add(this._attackComboAnimationNames[i], Animator.StringToHash(this._attackComboAnimationNames[i]));
        }

        this.StartCoroutine(this.CheckForCombo());
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            this._attackFlag = true;

            if (some attack cooldown check)
            {
                this.Attack();
            }
        }
    }

    [SerializeField] private float _attackComboTimeDifference = 1f;
    private float _lastAttackTime;
    public void Attack()
    {
        // Some attacking code
        // ......
        // end

        if (Time.time - this._lastAttackTime > this._attackComboTimeDifference)
            this.ResetCombo();

        this.PlayNextCombo();

        this._lastAttackTime = Time.time;
    }

    // or

    private bool _attackFlag;
    private bool _comboFlag;
    public void Attack()
    {
        // This is just to ensure that you don't attack till check for combo is completed (it's some kind of cooldown)
        if (this._comboFlag)
        {
            // Some attacking code
            // ......
            // end

            this.PlayNextCombo();

            this._comboFlag = false;
        }
    }

    private IEnumerator CheckForCombo()
    {
        while (true)
        {
            // Simple, we wait for some time, if player pressed attack then we don't reset combo
            // If he has been IDLE, we reset it
            yield return new WaitForSecondsRealtime(this._attackComboTimeDifference);

            if (!this._attackFlag)
                this.ResetCombo();

            this._attackFlag = false;

            this._comboFlag = true;
        }
    }

    private void PlayNextCombo()
    {
        this._animator.SetTrigger(this._attackComboAnimationNames[this._nextComboAttackIndex]);

        this._nextComboAttackIndex = (this._nextComboAttackIndex + 1) % this._attackComboAnimationNames.Length;
    }

    private void ResetCombo()
    {
        this._nextComboAttackIndex = 0;
    }
}

```

# Answer
> 0 votes
You could make use of **Combining Enumerator values with Bit-wise Operations**, that way you can define a set of actions, and combine them on the same Enum value, and then check if a certain flag was activated. I use this for Animator controller operations, since some states may depend on multiple states to be on.

As for the combo checking, you could make use of co-routines to have a timing for combo checking, as already suggested. Example (I'll assume you've read the page I attached):

```
public enum PlayerActions
{
    Idle = 0,
    Attack = 1,
    Jump = 2,
    Defend = 4,
    SpecialAttack = 8,
    Die = 16
}

public class Player : MonoBehaviour
{
    public Coroutine comboCheck;
    public float comboWait;
    public KeyCode attackKey;
    public KeyCode jumpKey;
    private PlayerActions actions;
    private Animator animator;

    void Awake()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        TrackActions();
        UpdateAnimator();
    }

    void UpdateAnimator()
    {
        animator.SetBool("Attack", (actions & PlayerActions.Attack) == PlayerActions.Attack);
        animator.SetBool("Jump", (actions & PlayerActions.Jump) == PlayerActions.Jump);
        animator.SetBool("Defend", (actions & PlayerActions.Defend) == PlayerActions.Defend);
        animator.SetBool("SpecialAttack", (actions & PlayerActions.SpecialAttack) == PlayerActions.SpecialAttack);
        animator.SetBool("Die", (actions & PlayerActions.Die) == PlayerActions.Die);
    }

    void TrackActions()
    {
        if(Input.GetKey(attackKey)) actions |= PlayerActions.Attack;
        else if((actions & PlayerActions.Attack) == PlayerActions.Attack && comboCheck == null) actions ^= PlayerActions.Attack;

        if(Input.GetKey(jumpKey)) actions |= PlayerActions.Jump;
        else if((actions & PlayerActions.Jump) == PlayerActions.Jump && comboCheck == null) actions ^= PlayerActions.Jump;

        if(comboCheck == null) comboCheck = StartCoroutine(ComboCheck());
    }

    IEnumerator ComboCheck()
    {
        WaitForSeconds wait = new WaitForSeconds(comboWait);
        yield return wait;

        // Your combo criteria:
        if((actions & PlayerActions.Jump) == PlayerActions.Jump && (actions & PlayerActions.Attack) == PlayerActions.Attack)
        {
            // Do some cool Jump + Attack wombo combo...
        }
    }
}

```

**NOTE:** The bit-wise operation enums are a suggestion to keep track of multiple states under just one variable, it is cheaper in memory, and easier to maintain than having n quantity of bools for n quantity of states. So, bools would also make the trick.

Hope it helps.

# Answer
> 0 votes
Here's how I managed the combo system of one of my Unity project:

My game has 3 attacks buttons which each has different combos. Each of those attacks has their own Bool parameter in the animator. In my case, the 3 are isUsingWeapon, isUsingSkill and isUsingAbility. (To put you in context, skills is related to the player's class and the ability is related to the player's race.)

Each attack are linked in a way that makes it so that the first attack of each attack buttons starts next to the previous attack. This allows me to set up as many possible combos as I want so that I'm not forced to have the same amount of attacks in a combo in every patterns.

The one thing I didn't script the same way as a typical fighting game is the fact that the player doesn't have to release any attack button if he/she wants to keep attacking. Kinda like how action-RPG works where you hold the mouse button and it keeps attacking and reset the combo when it's released. Did that with all 3 attacks buttons. This is also a LOT more simpler and efficient if you consider online with the possible issues of input lags over the network.

The way the combo works is that as you hold the button of an attack, whenever any animation state ends and reach its transition stage, it looks up what key is being held and and what direction and that's what determines which animation states it move toward at that point. This also allow the player to change the course of his action mid-animation. For example, the player hold the attack button as he think he can deal the 3rd attack of the combo, but at the last sec the opponent does something... the player release the attack button before the transition in the Animator is reached and that will allow him to do something else. If the animation state does reach the animation transition, then it's too late and that was a mistake on the player's part.

I call this kind of combat system: The trainer system. In a typical combat game, you usually take control of the fighter and timing of each buttons press is really important. In this system, you take control of the fighter's decision, but let the animation controls what's actually happening in the game. Instead of telling the character "attack, attack, attack, block, etc.", you tell him "Keep Attacking until I tell you to block". Way less complicated for the player which also allow younger players to have fun without having to learn how to time their button press in a way-to-precise way.

This idea came to me from the concept of how we script walking animations. Do we script "each steps individually" or do we just script the movement, add the walking animation over it and, if necessary, add the reverse IK's to allow the feets to always be on the ground? I basically use the same principle with the combos. Have X number of attack animations in rows and/or columbs (depending on what input controls the attacks) and look-up what's pressed each time an attack ends through the transition's conditions. You already looks at the input for movement and attacks so it's more of setting up the right conditions instead of going for the long "check animation state through script and script things in a way that counts input lags, frameskips, different controls sources, etc.

The only issue with this method is how much of a cluster the animator can become if you don't put the nodes in a clear way right as you create them. There are ways to make it visually simple, but it's ultimately the same thing, just visually different anyway.

---
Tags: unity, c#, game-design, animation, combat
---


# Question
Title: how do I set an int to the scroll wheel data in unity
i need to set an int to data from the scroll wheel so I can have the script use this int to display an item attached to a number from that int. i'm using c#

i set up my scroll wheel input, what am i doing wrong?

here is the script;

```
  counter = Mathf.RoundToInt(Input.GetAxis("ScrollWheel"));

    Items.text = counter.ToString();

```

# Answer
> 1 votes
`Mathf.RoundToInt()` is not a conversion method, you must use a technique called casts.

Try converting from float to int:

```
int scrollWheel = (int) Input.GetAxis("ScrollWheel");

```

Tell me if it works.

---

To explain, by putting `int` at the start of the line the next word becomes a new `int` or integer. We then get the value of `Input.GetAxis("ScrollWheel")`, and use `(int)` to convert it from `float` to `int` so the types are compatible.

The reason `Mathf.RoundToInt()` will not work properly is because **it ROUNDS the number to the nearest integer, as a math term, NOT the programming term.** (see Integers - Math Reference) For example, if you have a number that is 0.5 and used RoundToInt(), it returns 1 (the closest integer.)

What you're looking for is a way to **CONVERT** from float to int. The above code is how to do so.

---
Tags: unity, c#
---


# Question
Title: How to make sound play when button is pressed
I'm using Game Maker Studio 2.

When I press the "Z" key I need audio to play, but I can't seem to get it to work.

I'm using the following code inside an object's Key Press event:

```
if keyboard_check_pressed("Z")
{
   audio_play_sound(snd_menu_selection,1,false);
}

```

# Answer
> 1 votes
Maybe you have some misconception on the use of Game maker events.

Use the keyboard\_check\_ form when you are checking for key input in step event.

If you use the Key event there's no need for keyboard\_check\_ because it is already checking for the key to be pressed.

As you have your code, it will check "Z" key is pressed twice simultaneously (that's maybe impossible to perform XD), just keep the audio\_play\_sound line in the key event.

---
Tags: game-maker, sound-effects
---


# Question
Title: Alternatives to Camera.main.ScreenToWorldPoint in Unity
What are alternatives to `Camera.main.ScreenToWorldPoint` in Unity?

So, here is my code (just the piece which is relevant for the question):

```
void sendPointerMove(ref Vector3 mousePosition)
{
    lastMousePosition = mousePosition;

    Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    PointerData pointerData = new PointerData(
       mousePositionInWorld: mousePositionInWorld
    );
}

void FixedUpdate()
{
    Vector3 mousePosition = Input.mousePosition;

    if (needToSendPointerMove(mousePosition))
    {
       sendPointerMove(ref mousePosition);
    }
}

```

I am using JetBrains Rider to develop for Unity. And the ide suggests me the following about my `sendPointerMove` function invocation inside the `FixedUpdate`:

> Expensive method invocation

I am sure that the issue is due to the `Camera.main.ScreenToWorldPoint` because when I comment out the part the warning disappears.

Thank you.

# Answer
Basically, when you call `Camera.main`, Unity internally uses the `FindGameObjectsWithTag` to search through all of the objects in your scene that have the 'MainCamera' tag, returning the first active one. Since this will always be slower than a direct reference to it, you should cache it. You can declare it as a member variable and then initialize it inside your Start function.

This sort of pseudo code gives an example

```
using UnityEngine;

public class MyScript : MonoBehaviour
{
    Camera cam;

    void Start()
    {
        cam = Camera.main;
    }

    void ConvertMousePos()
    {
        Vector3 mousePositionInWorld = cam.ScreenToWorldPoint(Input.mousePosition);
    }

    void FixedUpdate()
    {
        ConvertMousePos();
    }
}

```
> 3 votes

---
Tags: unity, camera, coordinates
---


# Question
Title: Unity - Scroll Rect shows buttons outside of the rectangle
I have this problem. I'm using a scroll rect to display a series of buttons, but I would make sure that as soon as the buttons (with the scroll rect), come out of a certain area (bounded by a panel), become invisible. to explain it better in the pictures. I would like the visible part of the list of buttons to stop where there is the black arrow, and then I would delete the part where I drew the red waves

# Answer
> 4 votes
The component you're missing is the Mask. If you look at the official documentation for how to use a scroll rect. It'll show you that you need to put an Image component (even a mostly transparent one) on the parent container, and the Mask component. This will apply a mask to the children that go outside of the parent image. This results in all the stuff that's been scrolled outside of the parent to be hidden.

# Answer
> 0 votes
Use a RectMask to solve this problem. If you would like to have the scroll area a certain shape (like with rounded corners) then make sure the background image is part of the container object and use a regular Mask instead.

---
Tags: c#, unity, scrolling
---


# Question
Title: How to let players connect over the internet via TCP?
We are making a 2 player game, using a Client/Server architecture and need a way to connect over the internet.

Connecting in the same network is no problem and works flawlessly. Will it be a lot of work to implement a way to connect online, that players can use (so nothing where they need access to the router settings)? And how would it be done?

I couldn't find a single tutorial or thread talking about this. They all just connected to the localhost.

(using gamemaker studio 2 and it's built in tcp networking functions)

> edit:
>
> The server regularly sends broadcast packages to all ip's, while the client reads their origin ip and can then connect to said ip. They both are on the same subnet so the adrress is 192.168.0.xx.
>
> I also have a way to get the public ip (95.xxx.xxx.xx) using a http get from ipv4bot.whatismyipaddress.com. But when trying to connect to the server, using the public one, I't won't connect (doesn't matter if both are on the same network).

# Answer
> 1 votes
It is not possible for two computers, each behind a firewall, to directly connect to each other. Not without some kind of intermediary that's outside, or by opening up the firewall to outside connections that get routed to an internal host. This is like LAN 101 security that you don't allow directly connections inside your LAN. You let connections come out, but not in.

It is possible if the computer acting as the server opens up their firewall to allow external connections, but this is both challenging for some game players to set up, and also insecure for the player's home network.

What you need is something to act as a broker between the two players. Both machines connect outside, to a mutually agreed server. That server then acts as the broker for the communications to share what one sends, and have it be received by the other. Something outside their firewalls needs to manage the connection between them. There is really no way around this.

I would suggest using XMPP (also known as Jabber) as the protocol and method to communicate between the players. It is an open messaging protocol that works over TC/IP that will let you pass messages between two systems using an intermediary server. You can read more about XMPP at https://xmpp.org/

There are a number of public servers for it that can work as the intermediary, which you can find at https://list.jabber.at/ Using a public server, you can get around not having an active server of your own.

Basically both of your game clients will use the XMPP server just like they were two clients using chat, but will send data packets to each other.

There is an assumption here that you don't need to send a massive amount of data, and that you trust both clients to not cheat, since you will have no traditional centralized server that is the arbitrator of game actions.

---
Tags: networking, game-maker, matchmaking
---


# Question
Title: GameMaker Studio: fullscreen vs. dialogs
When setting my game to fullscreen, I get problems with dialogs:

* "get\_save\_filename" opens in the background, and when I close it, the game doesn't react anymore.
* Asking the user a yes/no question exits fullscreen mode and does not enter it again afterwards.
* "window\_set\_fullscreen" doesn't seem to do anything either...

Can anyone help?

# Answer
> 0 votes
By "get\_save\_filename" dialog, I assume you mean windows dialog to save/load your game somewhere? Here's a few tips:

* You could potentially make a custom file explorer inside the game, which I don't really recommend, but a lot of games do it and it works.
* You can simply save/load files only in the game's directory, so when you are about to save the game, the only thing you ask from the user is a slot number, so each user can have their own save.
* I haven't done gaming in windows for a while, but I assume when you say "Yes/no" questions you mean opening a windows GUI that asks the user a question. From what I remember, when windows has a game fullscreen, it likes to focus on it, so any pop-up would force the game to be minimised, and potentially unload/load assets all over again. If you want your game fullscreen, you don't want to have pop-ups. To be fair, for most games, you don't want GUI pop-ups anyway, as they break immersion with the game.

---
Tags: game-maker
---


# Question
Title: Why when a certain boolean variable is true, the Unity editor crashes?
In my game I've got a timer script, which counts down unless the game is paused, but whenever the variable for pausing is true, something in the timer script makes the editor itself crash, and I have to pull out the task manager to close unity because it freezes up completely.

Timer.cs

```
using UnityEngine;
using System.Collections;

public class Timer : MonoBehaviour {

  public LevelManager levelManager;

  // Use this for initialization
  void Start () {
    levelManager = FindObjectOfType<LevelManager>();
    StartCoroutine ("timerUpdate");
  }

  // Update is called once per frame
  void Update () {
  }

  IEnumerator timerUpdate (){
    while (levelManager.levelTimeSeconds>0) {
      if (levelManager.isPause== false){
        yield return new WaitForSeconds(1);
        levelManager.levelTimeSeconds -= 1;
      }
    }
    levelManager.isOver = true;
  }
}

```

Anyone have any idea what's causing the editor to crash once `isPause` is true?

# Answer
when it becomes true your loop will run forever :) Better use:

```
while (levelManager.levelTimeSeconds>0 && levelManager.isPause== false)
{
        yield return new WaitForSeconds(1);
        levelManager.levelTimeSeconds -= 1;
}

```
> 2 votes

# Answer
While loops must be used **WITH CAUTION**. A lot of times if `while` is not used in a correct manner it will always be `true`. Infinite loops can cause a program to crash, freeze or hang, like you experienced.

If dealing with arrays, use `foreach` instead if possible.

In case you're new to `foreach` syntax:

```
foreach (type elementname in variablename) { /*code here*/ }

```
> -1 votes

---
Tags: unity, debugging
---


# Question
Title: Manual collision detection with a Box Collider 2D
My game is turn-based, so I only need collision to be detected after a specific game event has occurred, so for instance after every PlayerMoveComplete event.

I could just define a MonoBehaviour representing a rectangle and check if player is within its bounds, like:

```
class MyRect {

 void OnMoveComplete () {
    // if player lies within the specified rectangle
    if (this.Contains(player.transform.position))
       DoSomething();
 }
}

```

But I like to be able to see and adjust the area inside the editor similar to a Box Collider 2d.

I think I could also use the default box collider 2d implementation like:

```
collider2D.bounds.Contains(pos)

```

But I'm not sure if it'd still do all those calculations even if I do not implement any of its message handling methods like OnCollisionEnter2D. If it does it's an overhead for the task.

# Answer
I assume you want to optimize the physics. And that was the main reason of this question.

If your game isn't using any physics that depend on frame rate and uses physics only at some points in time defined by game logic - you can turn off physics calculations and simulate them when necessary Physics.Simulate. This will greatly improve the performance of a game that has physics components used in great quantities.

To improve the performance you might as well look at Physics Best Practices \- use physics on separate layers, collision matrix will help. Make use of `LayerMask`s. Use raycasts in an optimized way.

As per your question:

You can cache colliders and use them in components. Code is untested and might contain some typos. As well some of the colliders might not have \`bounds.

```
[RequireComponent(typeof(Collider2D))]
public class Interactable2D : MonoBehaviour
{
    [SerializeField] private Collider2D _collider2D;

    protected virtual void Interact()
    {
        // Do something
    {

    public void Interact(Entity/Collider/Player entity)
    {
        if (this._collider2D.OverlapPoint(entity.transform.position))
            this.Interact();
    }

#if UNITY_EDITOR
    private void Reset()
    {
        this._collider2D = this.GetComponent<Collider2D>();
    }
#endif
}

```

Collider2D.OverlapPoint

`OnCollisionEnter2D` \- is an event, a message to be totally correct, though, from experience Unity probably caches function reference. It would be unwise to use reflection to call this method or any similar methods like `Start` or `Awake`...

It won't be invoked if you don't implement it. Calculations for `OverlapPoint` will only include calculations necessary to check if point is in bounds.

## My own suggestions

I would advise you to use Unity internal physics system instead of handling collision checks with `OverlapPoint` in case you are going to use it the way I have shown in the script (without additional collision detection). - Because - game engines usually use OcTree(3D), QuadTree(2D) to handle collisions. They separate collision detection in chunks. Because comparing collisions of every `Rigidbody/2D` with every `Collider/2D` is O(n\*m) (n - quantity of rigidbodies, m - quantity of colliders) - correct me if I am wrong. Which would be highly inefficient.

Without knowing your gameplay mechanics I can't be sure if you can use `OverlapPoint` efficiently. - I came up with those doubts because you would still need to know somehow against what `Entity/Collider/Player...` to check collisions.
> 2 votes

# Answer
I think you can use Physics2D.OverlapBox (*There are a few variation like Physics2D.OverlapCircle, Physics2D.OverlapArea and so on*). Basically it looks for colliders that overlaps within a range. See unity documentation for more info:

1. https://docs.unity3d.com/ScriptReference/Physics2D.html
2. https://docs.unity3d.com/ScriptReference/Physics2D.OverlapBox.html

For example, OnCompleteMovement you can just say

```
//Assuming this is written inside player script
void OnMoveComplete ()
{
    // checks 0.5 radius area around player and if any collision with layer "CheckPoint" found then return that collider info
    Collider2D col = Physics2D.OverlapCircle(transform.position, 0.5f,LayerMask.GetMask("CheckPoint"))
    // if we have hit the checkpoint
    if (col!=null)
       DoSomething();
}

```
> 0 votes

---
Tags: unity, collision-detection
---


# Question
Title: How do I implement 3D A* Pathfinding in libgdx?
I am using BDX (Blender with libgdx engine) to create my game. I am not sure on how to implement 3D path finding using A\* search. I looked into gdx-ai, but that is for 2D.

# Answer
Having used A\* path finding algorithms previously, my advice would be to take your Terrain, and break it down into smaller rectangles. Run a check to see if any of these rectangles co-inside with collidable entities. If they do, mark them as solid. From there, ensure each rectangle has a node, and continue as you would for calculating with 2D A\*.

When it comes to Y: This depends on how you have implemented the floor/terrain. Personally, I just set Y to be the height of the terrain at the current point. This works fine for me.

If you are also unfamiliar with A\* path finding in 2D, there is a really good game dev series by TheCherno on YouTube that covers this which i'd advise looking at.

Hope that helps!
> 1 votes

---
Tags: java, libgdx, android, blender
---


# Question
Title: In Unity on Android, how can I rotate an object with the accelerometer?
I'm making a game where you control a platform with balls falling on it, and you have to balance the balls and prevent them from falling off. I'm currently using a mouse to control it with this code:

```
transform.rotation.eulerAngles.z += Input.GetAxisRaw("Mouse X");
transform.rotation.eulerAngles.x += Input.GetAxisRaw("Mouse Y");

```

I'm trying to make this an Android app, and want to use motion controls so I can tilt the device, as if it were the platform. I figured I would use the accelerometer for this.

Any ideas on how to do this in Unity?

# Answer
> 0 votes
---

**Update:** As @Philipp mentioned in the comments section, Input.gyro is most likely what you are looking for. But this is a gyroscope if you are looking to use accelerometer then the answer is below. Accelerometer can also be used to determine rotation according to this: https://stackoverflow.com/a/5670134/6603717 .

Input.gyro

---

```
public class AccelerometerRotation : MonoBehaviour
{
    [SerializeField] private float _speed = 5f;

    private void Update()
    {
        Vector3 accRotation = new Vector3 (Input.acceleration.x, 0.0f, Input.acceleration.y);
        this.transform.Rotate(accRotation * this._speed * Time.deltaTime);
    }
}

```

Input.acceleration

Transform.Rotate

---
Tags: unity, android, accelerometer
---


# Question
Title: Why does my Vuforia 8.0 AR app work with a PC webcam, but not with a phone camera, and how do I fix it?
I am making an AR recognition app, the first time I have done so in 2018.3. I have installed the database and target info from the Vuforia developer portal. I have imported my model, and created an animator controller. I have an app key in place from Vuforia.

In Game mode using an attached webcam, the detection looks and works great, and the state manager correctly begins the animation. Cool.

Building for Android 7 proceeds without problem or console error. The app launches, but after target recco, only a small flickering portion of the model appears over the target... in fact, I **assume** it is the model, but it looks weird and meshy, as though it is cut off with straight edges.

Changing distance and angle with the phone camera does not change. Changing the scale of the object in Unity and recompiling does not change.

The behavior I am seeing does not occur if I replace my model with default cube. I also recalculated normals, and lowered the poly count: still no luck.

All input welcome.

# Answer
> 0 votes
My answer: Too many polys. The model was higher poly count that the phone could drive.

---
Tags: unity, augmented-reality, vuforia
---


# Question
Title: Unity animation editor having trouble to animate twice the same component
I'm not getting warm with the Unity animation editor.

This is what I want to do:

The 2 lasers should be like this, rotating 360 degrees over and over. .The classname laser2 doesn't mean anything, I implemented 2 concepts therefore this is the laser2 class. However, the animation editor seems to have a problem with having the same component more than once. I'm only able to animate the first laser.

As soon as I open the Laser2 section, it opens both lasers and changes in it are only stored in the first laser. Is there way to make them seperate? Having the exact same class twice (with different name) will help but that's an unbelievable dirty solution. I did not do much with the animation editor so far so maybe there is some easy fix that. Edit: Startangle is the value which must be animated on both.

# Answer
> 1 votes
Make them separate game objects with a shared parent node, so you only have 1 instance of the script on each object. Put the Animation component on the parent, and you can animate each child independently.

# Answer
> 0 votes
Is one laser object the parent of the other by chance? If so then it's animations will always override the child laser, so be sure to make them two separate objects. I'd suggest placing them inside one empty parent GameObject alongside all of the level terrain/walls.

# Answer
> 0 votes
The animator uses the NAME as reference. Not the GUID. The solution is simple:

1. Make a Gameobject without the Laser-scripts
2. Make 2 or more Children (with different Gameobject-names).
3. Add the Laser Script to the children.

---
Tags: c#, unity, animation
---