# Question
Title: Getting an error while building the Game for an Android Phone
I placed an Admob Plugin in my game. Then I import gamedonia SDK for Facebook connection and Push notification. In editor it's working fine. While compiling it for an Android Phone it generates an error. How can I fix this?

I am using Unity 5.2.

```
CommandInvokationFailure: Unable to convert classes into dex format. See the Console for details.
C:/Program Files/Java/jdk1.8.0_66\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "D:\Unity\unity 5.2.1\Unity\Editor\Data\PlaybackEngines\androidplayer/Tools\sdktools.jar" -

stderr[
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoIcsImpl;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoJellyBeanMr2;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoStubImpl;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompatIcs;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompatJellyBeanMr2;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/app/ActionBarDrawerToggle;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Landroid/support/v4/app/ActionBarDrawerToggle$1;

UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.RuntimeException: Translation has been interrupted
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:608)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:311)
    at com.android.dx.command.dexer.Main.run(Main.java:277)
    at com.android.dx.command.dexer.Main.main(Main.java:245)
    at com.android.dx.command.Main.main(Main.java:106)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at SDKMain.main(SDKMain.java:129)
Caused by: java.lang.InterruptedException: Too many errors
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:600)
    ... 9 more
]
stdout[
ignored resource E:\Unity3d 5.2.1 work Space\NGUI\Temp\StagingArea\android-libraries\GoogleMobileAdsPlugin\libs\.\PLUGIN_JAR_GOES_HERE
processing archive E:\Unity3d 5.2.1 work Space\NGUI\Temp\StagingArea\android-libraries\GoogleMobileAdsPlugin\libs\.\unity-plugin-library.jar...
ignored resource META-INF/
ignored resource META-INF/MANIFEST.MF
ignored resource com/
ignored resource com/google/
ignored resource com/google/unity/
processing com/google/unity/BuildConfig.class...
ignored resource com/google/unity/ads/
processing com/google/unity/ads/Banner.class...
processing com/google/unity/ads/Banner$1.class...
processing com/google/unity/ads/Banner$1$1.class...
processing com/google/unity/ads/Banner$2.class...
processing com/google/unity/ads/Banner$3.class...
processing com/google/unity/ads/Banner$4.class...
processing com/google/unity/ads/Banner$5.class...
processing com/google/unity/ads/Interstitial.class...
processing com/google/unity/ads/Interstitial$1.class...
processing com/google/unity/ads/Interstitial$1$1.class...
processing com/google/unity/ads/Interstitial$2.class...
processing com/google/unity/ads/Interstitial$3.class...
processing com/google/unity/ads/Interstitial$4.class...
processing com/google/unity/ads/Interstitial$5.class...
processing com/google/unity/ads/PluginUtils.class...
processing com/google/unity/ads/RewardBasedVideo.class...
processing com/google/unity/ads/RewardBasedVideo$1.class...
processing com/google/unity/ads/RewardBasedVideo$1$1.class...
processing com/google/unity/ads/RewardBasedVideo$2.class...
processing com/google/unity/ads/RewardBasedVideo$3.class...
processing com/google/unity/ads/UnityBannerAdListener.class...
processing com/google/unity/ads/UnityInterstitialAdListener.class...
processing com/google/unity/ads/UnityRewardBasedVideoAdListener.class...
processing archive E:\Unity3d 5.2.1 work Space\NGUI\Temp\StagingArea\android-libraries\appcompat-v7-23.1.1\bin\classes.jar...
ignored resource .readme
ignored resource META-INF/
ignored resource META-INF/MANIFEST.MF
ignored resource android/
ignored resource android/support/
ignored resource android/support/v7/
ignored resource android/support/v7/app/
processing android/support/v7/app/ActionBar.class...
processing android/support/v7/app/ActionBar$DisplayOptions.class...
processing android/support/v7/app/ActionBar$LayoutParams.class...
processing android/support/v7/app/ActionBar$NavigationMode.class...
processing android/support/v7/app/ActionBar$OnMenuVisibilityListener.class...
processing android/support/v7/app/ActionBar$OnNavigationListener.class...
processing android/support/v7/app/ActionBar$Tab.class...
processing android/support/v7/app/ActionBar$TabListener.class...
processing android/support/v7/app/ActionBarActivity.class...
processing android/support/v7/app/ActionBarDrawerToggle.class...
processing android/support/v7/app/ActionBarDrawerToggle$1.class...
processing android/support/v7/app/ActionBarDrawerToggle$Delegate.class...
processing android/support/v7/app/ActionBarDrawerToggle$DelegateProvider.class...
processing android/support/v7/app/ActionBarDrawerToggle$DrawerArrowDrawableToggle.class...
processing android/support/v7/app/ActionBarDrawerToggle$DrawerToggle.class...
processing android/support/v7/app/ActionBarDrawerToggle$DummyDelegate.class...
processing android/support/v7/app/ActionBarDrawerToggle$HoneycombDelegate.class...
processing android/support/v7/app/ActionBarDrawerToggle$JellybeanMr2Delegate.class...
processing android/support/v7/app/ActionBarDrawerToggle$ToolbarCompatDelegate.class...
processing android/support/v7/app/ActionBarDrawerToggleHoneycomb.class...
processing android/support/v7/app/ActionBarDrawerToggleHoneycomb$SetIndicatorInfo.class...
processing android/support/v7/app/AlertController.class...
processing android/support/v7/app/AlertController$1.class...
processing android/support/v7/app/AlertController$2.class...
processing android/support/v7/app/AlertController$3.class...
processing android/support/v7/app/AlertController$4.class...
processing android/support/v7/app/AlertController$5.class...
processing android/support/v7/app/AlertController$AlertParams.class...
processing android/support/v7/app/AlertController$AlertParams$1.class...
processing android/support/v7/app/AlertController$AlertParams$2.class...
processing android/support/v7/app/AlertController$AlertParams$3.class...
processing android/support/v7/app/AlertController$AlertParams$4.class...
processing android/support/v7/app/AlertController$AlertParams$OnPrepareListViewListener.class...
processing android/support/v7/app/AlertController$ButtonHandler.class...
processing android/support/v7/app/AlertController$CheckedItemAdapter.class...
processing android/support/v7/app/AlertDialog.class...
processing android/support/v7/app/AlertDialog$Builder.class...
processing android/support/v7/app/AppCompatActivity.class...
processing android/support/v7/app/AppCompatCallback.class...
processing android/support/v7/app/AppCompatDelegate.class...
processing android/support/v7/app/AppCompatDelegateImplBase.class...
processing android/support/v7/app/AppCompatDelegateImplBase$1.class...
processing android/support/v7/app/AppCompatDelegateImplBase$ActionBarDrawableToggleImpl.class...
processing android/support/v7/app/AppCompatDelegateImplBase$AppCompatWindowCallbackBase.class...
processing android/support/v7/app/AppCompatDelegateImplV11.class...
processing android/support/v7/app/AppCompatDelegateImplV14.class...
processing android/support/v7/app/AppCompatDelegateImplV14$AppCompatWindowCallbackV14.class...
processing android/support/v7/app/AppCompatDelegateImplV23.class...
processing android/support/v7/app/AppCompatDelegateImplV23$AppCompatWindowCallbackV23.class...
processing android/support/v7/app/AppCompatDelegateImplV7.class...
processing android/support/v7/app/AppCompatDelegateImplV7$1.class...
processing android/support/v7/app/AppCompatDelegateImplV7$2.class...
processing android/support/v7/app/AppCompatDelegateImplV7$3.class...
processing android/support/v7/app/AppCompatDelegateImplV7$4.class...
processing android/support/v7/app/AppCompatDelegateImplV7$5.class...
processing android/support/v7/app/AppCompatDelegateImplV7$5$1.class...
processing android/support/v7/app/AppCompatDelegateImplV7$6.class...
processing android/support/v7/app/AppCompatDelegateImplV7$ActionMenuPresenterCallback.class...
processing android/support/v7/app/AppCompatDelegateImplV7$ActionModeCallbackWrapperV7.class...
processing android/support/v7/app/AppCompatDelegateImplV7$ActionModeCallbackWrapperV7$1.class...
processing android/support/v7/app/AppCompatDelegateImplV7$ListMenuDecorView.class...
processing android/support/v7/app/AppCompatDelegateImplV7$PanelFeatureState.class...
processing android/support/v7/app/AppCompatDelegateImplV7$PanelFeatureState$SavedState.class...
processing android/support/v7/app/AppCompatDelegateImplV7$PanelFeatureState$SavedState$1.class...
processing android/support/v7/app/AppCompatDelegateImplV7$PanelMenuPresenterCallback.class...
processing android/support/v7/app/AppCompatDialog.class...
processing android/support/v7/app/AppCompatDialogFragment.class...
processing android/support/v7/app/AppCompatViewInflater.class...
processing android/support/v7/app/AppCompatViewInflater$DeclaredOnClickListener.class...
processing android/support/v7/app/NavItemSelectedListener.class...
processing android/support/v7/app/NotificationCompat.class...
processing android/support/v7/app/NotificationCompat$1.class...
processing android/support/v7/app/NotificationCompat$Builder.class...
processing android/support/v7/app/NotificationCompat$IceCreamSandwichExtender.class...
processing android/support/v7/app/NotificationCompat$JellybeanExtender.class...
processing android/support/v7/app/NotificationCompat$LollipopExtender.class...
processing android/support/v7/app/NotificationCompat$MediaStyle.class...
processing android/support/v7/app/NotificationCompatImpl21.class...
processing android/support/v7/app/NotificationCompatImplBase.class...
processing android/support/v7/app/ToolbarActionBar.class...
processing android/support/v7/app/ToolbarActionBar$1.class...
processing android/support/v7/app/ToolbarActionBar$2.class...
processing android/support/v7/app/ToolbarActionBar$ActionMenuPresenterCallback.class...
processing android/support/v7/app/ToolbarActionBar$MenuBuilderCallback.class...
processing android/support/v7/app/ToolbarActionBar$PanelMenuPresenterCallback.class...
processing android/support/v7/app/ToolbarActionBar$ToolbarCallbackWrapper.class...
processing android/support/v7/app/TwilightCalculator.class...
processing android/support/v7/app/TwilightManager.class...
processing android/support/v7/app/TwilightManager$1.class...
processing android/support/v7/app/TwilightManager$TwilightState.class...
processing android/support/v7/app/WindowDecorActionBar.class...
processing android/support/v7/app/WindowDecorActionBar$1.class...
processing android/support/v7/app/WindowDecorActionBar$2.class...
processing android/support/v7/app/WindowDecorActionBar$3.class...
processing android/support/v7/app/WindowDecorActionBar$ActionModeImpl.class...
processing android/support/v7/app/WindowDecorActionBar$TabImpl.class...
ignored resource android/support/v7/appcompat/
processing android/support/v7/appcompat/BuildConfig.class...
ignored resource android/support/v7/graphics/
ignored resource android/support/v7/graphics/drawable/
processing android/support/v7/graphics/drawable/DrawableUtils.class...
processing android/support/v7/graphics/drawable/DrawableWrapper.class...
processing android/support/v7/graphics/drawable/DrawerArrowDrawable.class...
processing android/support/v7/graphics/drawable/DrawerArrowDrawable$ArrowDirection.class...
ignored resource android/support/v7/text/
processing android/support/v7/text/AllCapsTransformationMethod.class...
ignored resource android/support/v7/transition/
processing android/support/v7/transition/ActionBarTransition.class...
ignored resource android/support/v7/view/
processing android/support/v7/view/ActionBarPolicy.class...
processing android/support/v7/view/ActionMode.class...
processing android/support/v7/view/ActionMode$Callback.class...
processing android/support/v7/view/CollapsibleActionView.class...
processing android/support/v7/view/ContextThemeWrapper.class...
processing android/support/v7/view/StandaloneActionMode.class...
processing android/support/v7/view/SupportActionModeWrapper.class...
processing android/support/v7/view/SupportActionModeWrapper$CallbackWrapper.class...
processing android/support/v7/view/SupportMenuInflater.class...
processing android/support/v7/view/SupportMenuInflater$InflatedOnMenuItemClickListener.class...
processing android/support/v7/view/SupportMenuInflater$MenuState.class...
processing android/support/v7/view/ViewPropertyAnimatorCompatSet.class...
processing android/support/v7/view/ViewPropertyAnimatorCompatSet$1.class...
processing android/support/v7/view/WindowCallbackWrapper.class...
ignored resource android/support/v7/view/menu/
processing android/support/v7/view/menu/ActionMenuItem.class...
processing android/support/v7/view/menu/ActionMenuItemView.class...
processing android/support/v7/view/menu/ActionMenuItemView$ActionMenuItemForwardingListener.class...
processing android/support/v7/view/menu/ActionMenuItemView$PopupCallback.class...
processing android/support/v7/view/menu/BaseMenuPresenter.class...
processing android/support/v7/view/menu/BaseMenuWrapper.class...
processing android/support/v7/view/menu/BaseWrapper.class...
processing android/support/v7/view/menu/ExpandedMenuView.class...
processing android/support/v7/view/menu/ListMenuItemView.class...
processing android/support/v7/view/menu/ListMenuPresenter.class...
processing android/support/v7/view/menu/ListMenuPresenter$MenuAdapter.class...
processing android/support/v7/view/menu/MenuBuilder.class...
processing android/support/v7/view/menu/MenuBuilder$Callback.class...
processing android/support/v7/view/menu/MenuBuilder$ItemInvoker.class...
processing android/support/v7/view/menu/MenuDialogHelper.class...
processing android/support/v7/view/menu/MenuItemImpl.class...
processing android/support/v7/view/menu/MenuItemImpl$1.class...
processing android/support/v7/view/menu/MenuItemWrapperICS.class...
processing android/support/v7/view/menu/MenuItemWrapperICS$ActionProviderWrapper.class...
processing android/support/v7/view/menu/MenuItemWrapperICS$CollapsibleActionViewWrapper.class...
processing android/support/v7/view/menu/MenuItemWrapperICS$OnActionExpandListenerWrapper.class...
processing android/support/v7/view/menu/MenuItemWrapperICS$OnMenuItemClickListenerWrapper.class...
processing android/support/v7/view/menu/MenuItemWrapperJB.class...
processing android/support/v7/view/menu/MenuItemWrapperJB$ActionProviderWrapperJB.class...
processing android/support/v7/view/menu/MenuPopupHelper.class...
processing android/support/v7/view/menu/MenuPopupHelper$MenuAdapter.class...
processing android/support/v7/view/menu/MenuPresenter.class...
processing android/support/v7/view/menu/MenuPresenter$Callback.class...
processing android/support/v7/view/menu/MenuView.class...
processing android/support/v7/view/menu/MenuView$ItemView.class...
processing android/support/v7/view/menu/MenuWrapperFactory.class...
processing android/support/v7/view/menu/MenuWrapperICS.class...
processing android/support/v7/view/menu/SubMenuBuilder.class...
processing android/support/v7/view/menu/SubMenuWrapperICS.class...
ignored resource android/support/v7/widget/
processing android/support/v7/widget/AbsActionBarView.class...<message truncated>

```

# Answer
> 0 votes
The gamedonia sdk and admob both plugin contain same class name. so i removed two jar files from my assets 1)Android-support-v4.jar and 2) google-play-service.jar. then i compiled. its build successfully.

Whenever import third party sdk's this can be happens. analysis the complete package and remove the unwanted files.

---
Tags: unity, google-play-services
---


# Question
Title: How can I position objects in a circular motion from the inspector
From the image below, I would like to position copies of my original circle (which is at the center) that are 1 unit away from the center and 30 degrees from each other in a circular motion. I would like to do this in the inspector. How can this be done?

# Answer
> 1 votes
1. Create a new empty game object and position it at the location of your inner disc.
2. Duplicate your inner disc (select it and press Ctrl/Command+D) and drag it under the empty game object in the hierarchy to make it a child of this parent.
3. In the inspector, move this child disc to position (1, 0, 0) - now it's the desired 1 unit away from the center.
4. Select the parent object and duplicate it. In the inspector, set the parent's rotation to (0, 0, 30). This makes a third disc 30 degrees away from the first.
5. Keep duplicating the parent and rotating each copy through 30 degree increments until you've completed your ring.
6. Expand all the parents in the hierarchy and select the discs inside. Drag them out from under the parents back to the containing level of the hierarchy. They'll automatically keep their positions consistent in their new home in the hierarchy.
7. While you still have all the discs of the ring selected, set their rotation in the inspector to (0, 0, 0) if you want them all oriented the same as the center disc.
8. Delete the now empty parent objects - they were just helpers to create the layout and we don't need them anymore.

---
Tags: unity
---


title: Unity Animation trouble

text:
# Question
Title: Unity Animation trouble
I am trying to make an animtion for my Sword so that when I click with my left mouse button, the sword gets swung. I watched a tutorial video and tried to follow all the steps but whats happening is that the Sword animtion gets played automatically in a loop

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

public class Sword : MonoBehaviour {

    void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
            GetComponent<Animation>().Play("Attack");
        }
    }
}

```

I know this isn't much to work with but maybe someone knows what I could have done wrong in the previous steps

# Answer
Try to go to your animation's asset and set **Loop Time** value to *false*. Depending on the type of animation asset, it might be called **Wrap Mode**, set it to *Once* in this case.
> 1 votes

# Answer
I got it to work now. The game pausing everytime I swung the sword, was because in the console, error pause was on, so everytime an error occurs, the game pauses.

And one of the errors was telling me something about it having to be marked as legacy and how to change that is by setting the inspector of the animation to "debug" as shown in the picture
> 0 votes

---
Tags: unity, unityscript
---


# Question
Title: I have a Unity addon that generates noise via a shader. How can I use it besides just dragging it onto a mesh?
I'm probably asking this question wrong. I'm using Turbulence Library to generate noise as shaders. What I want to do is take the noise generated by these shaders and apply them to Texture2Ds that I'm procedurally generating.

What I want to do is take the value of each pixel from the noise, then while procedurally generating a texture, use to determine how much I put another color "on top of" another color in a procedurally generated mesh. I would post an example picture, but I can't do that since I can only post one link with my reputation.

I strongly suspect that I will just have to write my own shader from scratch, but is there no way to just take noise from a shader and apply it to a Texture2D so I can continue to use the Standard shader?

# Answer
> 1 votes
I think Custom Render Textures is what you need: you can fill it with your own shader, use parameters from materials, assign it to texture slots (like a normal Texture2D), etc.

---
Tags: unity, shaders, textures, procedural-generation, perlin-noise
---


# Question
Title: Three.js— how to rotate sphere without moving light (using OrbitControls)?
Okay, I *think* the problem that I'm having is that when I create my `DirectionalLight` with three.js, when I then rotate my object with `OrbitControls` the entire *scene* is rotating, not just the sphere I have in the middle of it ( *the only object I have in my scene* ).

I want to make it so that I can rotate my sphere with my mouse like `OrbitControls` does, but not have the camera move. Or have the light not move with the camera? Here's a gif of my scene so far that might better explain my dilemma—

I want the light to be.. y'know.. more like the *sun*, coming from one point in space and shining at `(0,0,0)` in my scene, while still being able to rotate the sphere independently. Am I using `OrbitControls` wrong here? Here is what I have to get to the point I have in the gif above:

```
var width = section.offsetWidth,
height = section.offsetHeight;

var topOfElement = section.getBoundingClientRect().top - height;
var bottomOfElement = section.getBoundingClientRect().bottom;

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.position.z = 10;
camera.position.x = -2.5;

const controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableZoom = false;
controls.maxPolarAngle = Math.PI;

const renderer = new THREE.WebGLRenderer( { alpha: true } );
renderer.setClearColor( 0x000000, 0 );
renderer.setSize(width, height);
section.appendChild(renderer.domElement);

const onEverythingLoaded = () => {
    render();
};

const loadingManager = new THREE.LoadingManager(onEverythingLoaded);
const loader = new THREE.TextureLoader(loadingManager);

const earthGeomerty = new THREE.SphereGeometry( 5.5, 32, 32 );
const earthDiffuse = loader.load('assets/drought_earth_texture.png');
const earthSpec = loader.load('assets/drought_earth_texture_bump.png');

const material = new THREE.MeshPhongMaterial( {
    specular: 0xffffff,
    map: earthDiffuse,
    specularMap: earthSpec,
    normalScale: new THREE.Vector2( 1, 1 ),
    shininess: 30,
    transparent: true,
    depthTest: true,
    depthWrite: false,
    polygonOffset: true,
    polygonOffsetFactor: - 4,
    wireframe: false
} );

const sphere = new THREE.Mesh( earthGeomerty, material );
const ambientLight = new THREE.AmbientLight( 0x667777 );

const directionalLight = new THREE.DirectionalLight( 0xffffdd, 2 );
directionalLight.position.set( 4, 0, 0 );
scene.add( sphere );
scene.add( ambientLight );
scene.add( directionalLight );

const render = () => {
    animationFrame = requestAnimationFrame( render );
    sphere.rotation.y += 0.001;
    renderer.render( scene, camera );
};

```

For further clarification, I want to have my light work like this:

while still being able to rotate the earth with my mouse like with `OrbitControls`. But the light doesn't move.

Is `OrbitControls` the wrong tool here? Any documentation / helpful links would be appreciated I am so, so lost.

(I cross-posted this from stackoverflow because I thought maybe the people over here would know more about this, hope that's ok!)

## Update

After much fussing about with the `OrbitControls` functions I realised that what I'm trying to do isn't what `OrbitControls` is for, because "orbiting" isn't what I'm trying to do— I'm trying to rotate the *actual sphere* with my mouse, which is entirely different. Welp.

# Answer
> 3 votes
\[PROBLEM SOLVED\]

Hi!

I created the 'ObjectControls' module for ThreeJS that allows you to rotate a single OBJECT (or a Group), and not the SCENE.

You can find here a live demo https://albertopiras.github.io/threeJS-object-controls/

Here the repo https://github.com/albertopiras/threeJS-object-controls

It's very simple to use,

Hope this helps :)

Bye

Alberto

# Answer
> 2 votes
Turns out I was using the wrong thing for the job I was trying to do. `OrbitControls` .. y'know.. *orbits* the scene, and I wanted to rotate the sphere itself. I ended up implementing some mouse drag logic like so..

```
let isDragging = false;
let previousMousePosition = {
    x: 0,
    y: 0
};

const toRadians = (angle) => {
    return angle * (Math.PI / 180);
};

const toDegrees = (angle) => {
    return angle * (180 / Math.PI);
};

const renderArea = renderer.domElement;

renderArea.addEventListener('mousedown', (e) => {
    isDragging = true;
});

renderArea.addEventListener('mousemove', (e) => {
    let deltaMove = {
        x: e.offsetX-previousMousePosition.x,
        y: e.offsetY-previousMousePosition.y
    };

    if (isDragging) {

        let deltaRotationQuaternion = new THREE.Quaternion().

        setFromEuler(
            new THREE.Euler(toRadians(deltaMove.y * 1), toRadians(deltaMove.x * 1), 0, 'XYZ')
        );

        sphere.quaternion.multiplyQuaternions(deltaRotationQuaternion, sphere.quaternion);
    }

    previousMousePosition = {
        x: e.offsetX,
        y: e.offsetY
    };
});

document.addEventListener('mouseup', (e) => {
    isDragging = false;
});

```

.. and this drags my sphere around like I wanted to!

# Answer
> 2 votes
You can use `OrbitControls` for that. If using a directional light, the light will have a target (any object with a position). By default this is a `Vector3(0, 0, 0)`

Since it is the camera that is actually rotating (and moving), all you have to do is keep the light position the same as that of the camera.

```
light.position.copy(camera.position);

```

It took me a little while to wrap my head around that. I assumed rotation was applied to the scene, but it turns out: it's just a matter of following the camera position.

# Answer
> 1 votes
If you have nothing else in the scene you can fake it by moving the light source to the same (relative) direction as the camera before rendering.

`OrbitControls` will move the camera but if the light follows the camera it'll give the illusion that it's only the earth rotating.

Like a spaceship engine that moves the entire galaxy backward rather than move the ship forward.

Everything is relative.

---
Tags: javascript, three.js
---


# Question
Title: Problem with Factory Method Pattern when I try to create a Weapon:MonoBehaviour
I'm learning about Design Patterns using Unity and I'm not sure about how to solve the following problem with the Factory Method Pattern:

I want to read a XML file and using the Factory Method Pattern to create a Component (a Weapon) to add it to a GameObject which will be cointained on a Pool Manager, but Weapon "Is A" MonoBehaviour and for that reason It can't be instantiated using a "machineGun = new MachineGun();"

```
public abstract class WeaponFactoryMethod
{
    protected string fileName = "weapons.xml";
    public abstract Weapon CreateWeapon();
}

public class MachineGunFactoryMethod : WeaponFactoryMethod
{
    public override Weapon CreateWeapon()
    {
        string filePath = Path.Combine(Application.streamingAssetsPath, fileName);
        Weapon machineGun = null;
        XmlReader xmlReader = new XmlTextReader(filePath);
        if (xmlReader.ReadToDescendant("Weapons"))
        {
            if (xmlReader.ReadToDescendant("Weapon"))
            {
                do
                {
                    // I CAN'T DO THIS:
                    machineGun = new MachineGun();
                    machineGun.ReadXml(xmlReader);
                } while (xmlReader.ReadToNextSibling("Weapon"));
            }
            else
            {
                Debug.LogError("There aren't definition for Weapon");
            }
        }
        else
        {
            Debug.LogError("There aren't definition for any Weapon");
        }

        return machineGun;
    }
}

public abstract class Weapon : MonoBehaviour, IXmlSerializable
{
    public float AttackRange { get; set; }
    //Every weapons Shoots in a different way
    public abstract void Shoot();

    //Serialization
    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        XmlReader childReader = reader.ReadSubtree();
        while (childReader.Read())
        {
            switch (childReader.Name)
            {
                case "AttackRange":
                    childReader.Read();
                    AttackRange = childReader.ReadContentAsInt();
                    break;
            }
        }
    }

    public void WriteXml(XmlWriter writer)
    {

    }
}

public class MachineGun : Weapon
{
    public override void Shot()
    {
        //Raycasting..
    }
}

```

At the end I want something like

```
GameObject (player)
 - Component (A Weapon script with the data from the xml)

```

Should I just create a GameObject (player) and do an "AddComponent \< MachineGun \>" and later copy the info from the xml file instead using the Factory Method Pattern??

Is there a better way??

Any suggestions, corrections or advice will be very grateful.

I'm sorry by my English.

# Answer
> 0 votes
You're just not supplying your factory with the right parts to do its job. You can learn about another design pattern called dependency injection. Essentially, you pass the GameObject you want to be modified into the factory as an argument.

```
public override Weapon CreateWeapon(GameObject target){
...
             machineGun = target.AddComponent<MachineGun>()
             machineGun.ReadXml(xmlReader);
...
}

```

This will add the component to the GameObject and then read the XML to configure the component.

---
Tags: unity, design-patterns
---


# Question
Title: Making a sound every time I get to the edge of the platform
I'm trying to make a runner game for the blind, and I need help making a sound every time it is time to jump. I am using Game Maker, and I have no idea how to do it.

How do I play a sound when my player gets to the edge of a platform in Game Maker?

# Answer
A few methods you can use for this:

* Add an invisible block in front of the edge (where you want the sound to go off) and when the player hits this invisible block, delete the block and play the sound.
* Make the ground around the edge into a trigger so that when the player "steps onto" (interacts or collides with) that ground, you can know when to play the sound.
* Add an invisible block to your player that goes in front of him and detects collisions with other objects. Add invisible objects that only interact with this invisible block at the edges or on traps etc., and play a sound when they interact.

They're all valid methods and there may be many more that I can't think of right now, pick one that seems like you can implement and work on that, or make one up using these as general ideas of how to implement this mechanic.
> 1 votes

# Answer
Probably the cleanest way in the to implement this is to use a raycast slightly in front and under the player that detects when the floor is going to miss. By using this approach you can make the sound happening always at the same moment before a jump. You can also use the same trick to eventually detect obstacles.
> 1 votes

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


title: HDR alpha blend

text:
# Question
Title: HDR alpha blend
How do I blend two colors using SrcAlpha and OneMinusSrcAlpha when I have HDR range (rgb and a values can be \> 1)?

The typical formula for non-HDR is (src * srcAlpha) + (dst * (1.0 - srcAlpha)) but this generates a negative value if srcAlpha is \> 1.

# Answer
Clamp your srcAlpha between 0 and 1.

Your pixels can't be more opaque than 100% or more transparent than 0% opacity.
> 1 votes

---
Tags: alpha-blending, hdr
---


title: Raycasting from 3D object to UI canvas!

text:
# Question
Title: Raycasting from 3D object to UI canvas!
I have a world space canvas in front of the player and I want to shoot a ray towards an enemy (in the direction of the enemy) and create and object where Raycast hits the UI canvas.
I know that the physics engine doesn't interact with UI elements and event system is not the answer for me since it depends on pointer events and their position.
So how can I do this?
If possible, I would like to draw the ray or the line as gizmo to see if it's working.
My Current Code is this:

```
void OnDrawGizmos()
{
    foreach (AeroplaneAiControl item in GameObject.FindObjectsOfType<AeroplaneAiControl>())
    {
        Gizmos.color = Color.magenta;
        Gizmos.DrawLine(transform.position, item.transform.position);
        Vector3 Direction = transform.position - item.transform.position;
        RaycastHit rch;
        Ray r = new Ray(transform.position, Direction);
        Physics.Raycast(r, out rch);
        if (rch.collider != null)
        {
            Gizmos.color = Color.cyan;
            Gizmos.DrawLine(transform.position, rch.point);
            Gizmos.DrawSphere(rch.point, 0.1f);
        }
    }
}

```

it draws the magenta line but not the cyan line and no spheres.

# Answer
> 2 votes
The problem is with the ray casting code. By taking a look at the documentation page I realized that for getting the direction I have to subtract the player from target, and I was doing the opposite of this. So the results where not correct.

```
Vector3 Direction = transform.position - item.transform.position;

```

Should be changed to

```
Vector3 Direction = item.transform.position - transform.position;

```

---
Tags: unity, c#, gui, raycasting
---


# Question
Title: Fatal error in Game Maker: variable not set before reading it
I have been following the tutorial videos on game maker, and I am at the part where he explains how to get the bullet under the character. I thought I did everything right. He then tested the game, and it worked. But when I played, and tried to shoot, this message appeared:

---

\#

FATAL ERROR in action number 1 of Step Event0 for object obj\_player:

Variable obj\_player.layer\_bullet(100002, -2147483648) not set before reading it. at gml\_Object\_obj\_player\_Step\_0 (line 30) - instance\_create\_layer(x, y, layer\_bullet, obj\_bullet);

\#

# Answer
> 2 votes
Layers have to be referenced via their name, provided as a string. Try changing your create function in the step event to

```
instance_create_layer(x, y, "layer_bullet", obj_bullet

```

---
Tags: game-maker
---


title: How to remove skybox in unity using C#

text:
# Question
Title: How to remove skybox in unity using C#
How to change or remove Skybox on run time in unity using C#?

Is there any way to remove it while its not even required?

Or load it using http link for material we are using in Skybox.

# Answer
use this under any function if you want to remove for example in

```
void Update()
{ RenderSettings.skybox = (null);

```

or just use this RenderSetting.skybox = (null);

```
public material = skyboxMat;

```

to change skybox same `RenderSetting.skybox = skyboxMat;` is being used
> 1 votes

# Answer
In addition setting the skybox globally with `RenderSettings.skybox = newMaterial`, you can also set a skybox on the camera-level. This can be useful when you want to have different cameras with different skyboxes.

1. Add a Skybox component to the camera game object
2. Refer to it with `GetComponent<Skybox>().material = newMaterial`
> 0 votes

---
Tags: unity, skybox
---


# Question
Title: Unity AdMob plugin - rewarding the user on the main thread
There's a simple guide on the `Firebase`'s website on how to implement the `AdMob`'s rewarded video: https://firebase.google.com/docs/admob/unity/rewarded-video

Let's take some code:

```
public void OnVideoAdComplete(object sender, Reward reward){
    SoundMgr.Instance().PlayRewardSound();
    // double coins etc
}

```

Let's plug it in:

```
private void LoadVideoAd(){
    videoAd = RewardBasedVideoAd.Instance;

    AdRequest request = new AdRequest.Builder().AddTestDevice("XXXXXXXXXXXXX").Build();
    videoAd.LoadAd(request, androidVideoAdID);

    if(!videoCallbackSet){
        videoCallbackSet = true;
        videoAd.OnAdRewarded += OnVideoAdComplete;
    }
}

```

And now let's get a `ThreadException` cause we played a sound on the other thread:

```
Unity   : Function SoundChannelStopList::~SoundChannelStopList() may only be called from main thread!

Unity   : ExecutionEngineException: SIGILL
Unity   :   at SoundManager.PlaySuccess1Sound () [0x00000] in <filename unknown>:0
Unity   :   at Game.OnVideoAdClose () [0x00000] in <filename unknown>:0
Unity   :   at AdManager.OnVideoAdClose (System.Object sender, System.EventArgs args) [0x00000] in <filename unknown>:0
Unity   :   at GoogleMobileAds.Api.RewardBasedVideoAd.<RewardBasedVideoAd>m__4 (System.Object sender, System.EventArgs args) [0x00000] in <filename unknown>:0
Unity   :   at (wrapper delegate-invoke)
System.EventHandler`1<System.EventArgs>:invoke_void__this___object_EventArgs (object,System.EventArgs)
Unity   :   at GoogleMobileAds.Android.RewardBasedVideoAdClient.onAdClosed () [0x00000] in <filename unknown>:0
Unity   :   at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
Unity   : Rethrow as TargetInvocationException: GoogleMobileAds.Android.RewardBasedVideoAdClient.onAdClosed()
Unity   :   at UnityEngine.AndroidJavaPro

```

How is this possible that it's year 2017 and the most leading game engine's plugin is runnning it's callbacks without some sort of `App.PostRunnableOnMainThread()`?

Is there any workaround on this or we need to create an incredible pattern like:

```
update(){
    if(adFinished)
        //give rewards
    }

```

I'd be grateful for any tips! :)

# Answer
If you want to work with Unity and threads, you'll need to implement 2 features that are unfortunately absent from Unity: A thread pool and a main thread dispatcher.

```
using System;
using System.Collections.Generic;
using System.Threading;

public class UnityThreadPool : UnityEngine.MonoBehaviour
{
    Deque<Action> mMainThreadWaitQueue;
    Deque<Action> mCurrentlyProcessing;
    static UnityThreadPool sInstance;
    Pool mPool;

    public void EnqueueOnMain(Action task) { lock (mMainThreadWaitQueue) mMainThreadWaitQueue.AddToBack(task); }
    public void EnqueueOnWorker(Action task) { mPool.QueueTask(task); }
    public static UnityThreadPool Instance {
        get {
            if (sInstance == null)
                sInstance = new UnityEngine.GameObject("ThreadPool").AddComponent<UnityThreadPool>();
            return sInstance;
        }
    }

    void Awake()
    {
        UnityEngine.Debug.Assert(sInstance == null,"Multiple ThreadPools detected.");
        DontDestroyOnLoad(transform.gameObject);
        mPool = new Pool(UnityEngine.SystemInfo.processorCount);
        mMainThreadWaitQueue = new Deque<Action>(10);
        mCurrentlyProcessing = new Deque<Action>(10);
    }
    void Update()
    {
        lock (mMainThreadWaitQueue) {
            if (mMainThreadWaitQueue.Count == 0)
                return;
            UnityEngine.Debug.Assert(mCurrentlyProcessing.Count == 0);
            mCurrentlyProcessing.InsertRange(0,mMainThreadWaitQueue);
            mMainThreadWaitQueue.Clear();
        }
        var watch = System.Diagnostics.Stopwatch.StartNew(); // this is the main thread, track time so we don't block it for too long
        while (mCurrentlyProcessing.Count !=  0){
            var action = mCurrentlyProcessing.RemoveFromFront();
            try { action(); } catch (System.Exception e) { UnityEngine.Debug.LogError("Unhandled Exception in MainThread task: " + e.ToString()); }
            if (watch.ElapsedMilliseconds > 10) {
                lock (mMainThreadWaitQueue) { mMainThreadWaitQueue.InsertRange(0,mCurrentlyProcessing); }
                mCurrentlyProcessing.Clear();
                break;
            }
        }
    }
    void OnDestroy() { mPool.Dispose(); }
}

```

For an example implementation of `Pool` see: https://stackoverflow.com/a/436552/1612743

But chances are Unity will support the basic .Net threadpool in an upcoming version. If they do you won't need that part.
> 1 votes

# Answer
You can set a boolean value in the callback function as true, and in the main thread have an `Update()` function polling that value. Also just to be sure, you could use a `lock()`. Like this:

```
public class AdMobVideoRewarder : MonoBehaviour
{
    object threadLock = new object();
    bool videoShown;
    public void OnVideoAdComplete(object sender, Reward reward){
        lock(threadLock) videoShown = true;
    }
    void Update()
    {
        lock(threadLock)
        {
            if(videoShown)
            {
                videoshown = false;
                SoundMgr.Instance().PlayRewardSound();
            }
        }
    }
}

```

As a side note you should not have too complex code inside a `lock()` code block in the callback function as it will stall the main thread from executing. Also the lock may be too much in this case as it's only for setting one boolean value.
> 0 votes

---
Tags: unity, multithreading, admob
---


# Question
Title: How should I poll for component state changes when designing an ECS?
I'm implementing an ECS and have run into a predicament.

Let's say my main loop is something like (super simplified, all code below is pseudo-code)

```
while (true) {
    // timing logic in here somewhere
    for (GameSystem system : systems) {
        for (GameEntity entity : entities) {
            system.update(entity);
        }
    }
}

```

Components need to have their state updated, but how exactly that state gets updated is kind of blurry.

Let's say I have an `InputComponent` base type. There can be lots of `InputComponent` types, keyboard, controller, etc. *I* (as the game engine) don't really care that you pressed the `W` key with the intent to move up, or that you pressed the `Spacebar` key to jump. That is outside the scope of my concern. What I *do* care about is the intent. I *do* care that you want to move up, or to jump, but don't care how that command gets generated. How that command gets generated is up to the `InputComponent` to decide. Otherwise, I would have to dirty up my system code with something like

```
class MovementSystem {

    void update(GameEntity entity) {
        if (entity.getSettings().isUsingKeyboardInput()) {
            if (entity.getKeyboardInput().isSKeyPressed()) {
                moveDown();
            }
            else if (entity.getKeyboardInput().isWKeyPressed()) {
                moveUp();
            }
            // else if ...
        }
        else if (entity.getSettings().isUsingController()) {
            if (entity.getControllerInput().getMovementJoystick().isHeldDown()) {
                moveDown();
            }
            // ...
        }
    }
}

```

I don't want to have to care about all of those things. If they're using Dvorak or some other keyboard mapping, suddenly it doesn't work.

It only gets marginally better if I swap it from `isWKeyPressed` to `isUpKeyPressed`, but I still don't want to have to manage all of those things, figuring out which input method to use.

I'd like to abstract all that business away, I (being the game engine) want to be as dumb and as lazy as possible. So, I thought, perhaps, I could create something like a `MovementInputComponent` as a base type for a `KeyboardMovementInputComponent` or `ControllerMovementInputComponent`.

```
public interface MovementInputComponent {

    boolean isMovingUp();

    boolean isMovingDown();

    boolean isJumping();
}

```

Which makes it, again, a little bit better, changed to

```
void update(GameEntity entity) {
    if (entity.getInputComponent().isMovingUp()) {
        moveUp();
    }
    else if (entity.getInputComponent().isJumping()) {
        jump();
    }
    // ...
}

```

We don't need to check which type of input the player is using (keyboard/controller), which also means we don't need to muddy up the system code. We're doing better, but still not great, because...

I want to be able to host this in a client-server environment; or maybe just bundled all together on the users PC; or maybe have a thin-client on their mobile device. But the game engine stays the same. Nothing **must** change within the game engine, just because the user is using their phone, because it's still the same game. Same game, same rules.

Keeping in mind the possibility that this could be in a client-server architecture, I would need some way of being able to tell what the client is doing, potentially across the world. Okay, we'll make a `RemoteKeyboardMovementInputComponent` that looks something like

```
class RemoteKeyboardMovementInputComponent implements MovementInputComponent {

    private final Socket clientSocket;

    // ...

    @Override
    public void isMovingUp() {
        clientSocket.sendCheckForUpKeyPressedPacket();
        return waitForResponse(clientSocket);
    }
}

```

The system still has no idea on the mechanics of how this is being generated, but now we've added real, hard latency into the mix. If we have to send packets of data to request what keys the client has pressed, we're in for a 2FPS game, which just won't do. This leads me to...

**Why am I still in the business of the mechanics of actions?**

I thought I was getting away from having to worry about *how* a key was being pressed, but I just moved the problem further downstream. I don't want to have to worry about any of it. I don't want to see the word `Keyboard` or `Controller` anywhere in the game engine, because it shouldn't care. It should only care about the game world; nothing more, nothing less.

Fine, we know we haven't solved the root cause. I (the game engine) know that somehow, somewhere, I'm getting inputs from something, but I don't care about where. I just care about the intent; as well, I don't want to potentially poll some external resource for the current state, I want it to be readily available. This led me to the idea of having some sort of command queue that I could poll.

However, I still want to separate the concerns of the game *engine* from the game *server*; where the *engine* cares only about the things that happen within the world, and the *server* cares only about the packets that are being sent and received.

```
class GameServer implements Runnable {

    final PacketHandlerRepository packetHandlers;

    @Override
    public void run() {
        while (true) {
            for (Socket client : connectedClients) {
                if (client.hasPendingPacket()) {
                    Packet packet = client.getNextPacket();
                    PacketHandler handler = packetHandlers.getPacketHandler(packet);

                    handler.handle(packet);
                }
            }
        }
    }
}

class MoveUpPacketHandler implements PacketHandler {

    final Queue<GameAction> actionQueue;

    void handle(MoveUpPacket packet) {
        actionQueue.add(new MoveUpAction());
    }
}

```

So now we can share the action queue between the server and the engine.

```
class GameEngine implements Runnable {

    final Queue<GameAction> actionQueue;

    GameEngine(Queue<GameAction> actionQueue) {
        this.actionQueue = actionQueue;
    }

    @Override
    public void run() {
        // ...
    }
}

```

And now we get to the heart of the question (and perhaps, the reason for my initial title of *Multiple inputs per frame*...); I have this action queue, filled with the intentions of the players.

**How should we update the state of the components?**

Should we pop from the queue the next action, handle the action, and then continue processing through the systems like normal?

```
class MoveUpActionHandler implements ActionHandler<MoveUpAction> {

    final ComponentFinder componentFinder;

    void handle(MoveUpAction action) {
        Position position = componentFinder.findComponent(action.getEntityId(), Position.class);

        position.moveUp();
    }
}

// in GameEngine
while (true) {
    GameAction action = actionQueue.pop();
    ActionHandler handler = actionHandlers.getHandler(action);

    handler.handle(action);

    for (GameSystem system : systems) {
        for (GameEntity entity : entities) {
            system.update(entity);
        }
    }
}

```

Looking at this code, it seems vaguely reminiscent of a system, but instead of it being driven by components, its driven by actions; which means it's not really a system, it just kind of behaves like one (like how a tractor kind of behaves like a Ferrari).

Do we take multiple actions per frame? How would we decide what the right number is? Do we do something different all together that I haven't thought of?

# Answer
There may be a bit of a misunderstanding of how an ECS is intended to work here.

You shouldn't ever need to "poll" for state updates on components. In the ECS model, the components *are* the state. The systems should mutate components in-place or otherwise synchronize their changes to the components during their updates.

e.g., the `Position` component in your example should always contain the up-to-date position of its entity. Systems like physics should update the `Position` components of anything the system wants to move; any system updating later in sequence will thus automatically see the up-to-date position inside the `Position` component.

On a vaguely-related note, your main loop is a bit scary. You shouldn't loop over every entity for every system (an `N*M` operation!) but instead have each system keep its own internal list of relevant entities. e.g., the physics system probably only cares about entities that have both `Position` and `Shape`. When entities (or components) are created/destroyed, notify systems and let them register/deregister the entity if appropriate. The system can then keep tuples of component references (e.g., that physics system might have an array of `struct{position*, shape*}` objects so it can directly read and mutate the components/state it cares about; it might even make copies of immutable state into its own data structure for each more convenient or efficient access).
> 2 votes

# Answer
Input can be handled several ways at the lowest level and it really depends on the engine's design. Some engines provide a way to inject input, placing the burden of developing that code as a part of each individual application while other engines may expose a cross-platform module that allows the engine to poll/capture input from various devices as a part of its own main loop.

That aside, you're definitely on the right track by adding a translation step to your input processing if you wish to support any type of configurable key-binding solution. This *intent system* should be able to either poll for specific input state or react to a sequence of input state changes depending on the needs of the key-binding configuration.

The *intent system* effectively toggles various game specific state *ON* or *OFF*. This state could be something which is stored either on a component or a local system variable during the a system's update phase.

But whether your game runs in a client-server simulation or simply a local one, your local game simulation should always react to movement intent. In other words, when a user presses the `W` key, the user should move forward. This movement should be simulated locally to avoid any problems with the user's game play experience because of latency.

So then how do we make sure the user isn't cheating in a client-server simulation? This is precisely where periodic position validation needs to happen by the server.

Each frame, your code should package up all movement intent that was requested and send that along with the player's current position to the server. The server simulates the movement just like the client and compares its results to that of the client's position. If the server deems the client's position to be within a reasonable margin of error to the server's simulation, the server accepts the client's position and responds with nothing. Should the client's position be incorrect, the server will request the client to reset the player's position to the server's last good position (aka rubber bands the user back to a prior point).

So in a client-server simulation, the only difference here is the fact the server has authority to force the client to move the player to a specific position; otherwise, it simply performs the same simulation as the client and validates that the client isn't where it shouldn't be.
> 1 votes

---
Tags: entity-system
---


# Question
Title: How does the change ID increment in the Path of Exile API?
Does any body know how the next change ID increments on the POE API?

I think I have figured out the the API returns the latest, system wide next\_change\_id for the latest stash changes.. but in between refreshes the incrementations are a bit all over the place.

So these are the change id's reported within seconds of updates

```
97021553-101802592-95624331-110373614-103027614
97021579-101802666-95624405-110373692-103027683
97021579-101802668-95624405-110373695-103027694
97021579-101802668-95624405-110373710-103027694

```

It looks like a GUID but it is not a GUID by any means.. when the game started these numbers where allot lower.

I have tried searching forums for a more in depth breakdown of how the API works. The game site has limited information, Reddit has some insight and source code links.. but no proper break down.

# Answer
> 1 votes
I don't have any hard evidence but from tinkering with the change id myself I came to the conclusion that it represents 5 different ids. I assume they use 5 different databases/shards (maybe one for each region?) and each has its own identity column. As already mentioned you only need to set this as an initial value if you want to write a crawler. After the first request you should use the value that was provided with the response.

# Answer
> 0 votes
So this is not officialy documented any where but from what I have managed to gather is that the "number" is divided into five parts. Each part belongs to a shard. for example, US,EU,JP...

Each number is actually the number up updated "public and/or private" item changes recorded on the shard.

```
97021553-101802592-95624331-110373614-103027614

```

So shard\[0\] as some people like to call it has seen 97million and a bit item changes.

You can actually just get data from each shard by setting the other shard numbers at extremly high numbers.

```
0-9999999999-9999999999-9999999999-9999999999

```

will return a set of stashes and items ONLY belonging to shard\[0\] and the next change ID is

```
2524-9999999999-9999999999-9999999999-9999999999

```

Which means THIS request returned 2542 items from the start of the game, and on that next ID you get the next DELTA SET of data.

```
4888-9999999999-9999999999-9999999999-9999999999

```

This subset managed to return 2364 items for shard\[0\] (4888-2524) which is a similar data set size.

Now the **normal** API returns a number that looks a bit strange and is hard to follow because the API fills a buffer of about 5mb of uncompressed data, then calculates the new number just for your call, based on all the data it could get from ALL the shards. You then need to follow your change id's get the next set of data in sequence.

If you call a number that is over the amount of items seen on all shard you just get an empty response, with that change ID and no items. This is possible, if you can manage to catch up to real time.

But that is only possible if you do some clever maths your self.

And the maths is what makes sites like poe.trade able to det data indexed within seconds and is their "secret sauce"

---
Tags: modding
---


# Question
Title: 2D character controller in unity (trying to get old-school platformers back)
This days I'm trying to create a 2D character controller with unity (using phisics). I'm fairly new to physic engines and it is really hard to get the control feel I'm looking for. I would be really happy if anyone could suggest solution for a problem I'm finding:

This is my FixedUpdate right now:

```
public void FixedUpdate()
{
    Vector3 v=new Vector3(0,-10000*Time.fixedDeltaTime,0);
    _body.AddForce(v);

    v.y=0;
    if(state(MovementState.Left))
    {
        v.x=-_walkSpeed*Time.fixedDeltaTime+v.x;
        if(Mathf.Abs(v.x)>_maxWalkSpeed) v.x=-_maxWalkSpeed;
    }
    else if(state(MovementState.Right))
    {
        v.x= _walkSpeed*Time.fixedDeltaTime+v.x;
        if(Mathf.Abs(v.x)>_maxWalkSpeed) v.x=_maxWalkSpeed;
    }

    _body.velocity=v;

    Debug.Log("Velocity: "+_body.velocity);
}

```

I'm trying here to just move the rigid body applying a gravity and a linear force for left and right. I have setup a physic material that makes no bouncing and 0 friction when moving and 1 friction with stand still. The main problem is that I have colliders with slopes and the velocity changes from going up (slower) , going down the slope (faster) and walk on a straight collider (normal). How could this be fixed? As you see I'm applying allways same velocity for x axis.

For the player I have it setup with a sphere at feet position that is the rigidbody I'm applying forces to.

Any other tip that could make my life easier with this are welcomed :).

P.D. While coming home I have noticed I could solve this applying a constant force parallel to the surface the player is walking, but don't know if it is best method.

# Answer
> 7 votes
If you are looking to mimic old school platformers step one is to ditch physics altogether. You will end up fighting the physics system to get the decidedly non-realistic motion of an old school platformer. Have a look at this CharacterController replacement that ditches physics altogether to get a good idea of one way to implement it.

# Answer
> 3 votes
You'd probably be happier going with what mheona recommended. But if you're going to use Unity's physics, then you probably want to use `ForceMode.VelocityChange`.

Example:

```
public void FixedUpdate()
{
    var v = Vector3.zero;
    if(state(MovementState.Left))
    {
        v.x=-_walkSpeed*Time.fixedDeltaTime+v.x;
        if(Mathf.Abs(v.x)>_maxWalkSpeed) v.x=-_maxWalkSpeed;
    }
    else if(state(MovementState.Right))
    {
        v.x= _walkSpeed*Time.fixedDeltaTime+v.x;
        if(Mathf.Abs(v.x)>_maxWalkSpeed) v.x=_maxWalkSpeed;
    }

    _body.AddForce(v, ForceMode.VelocityChange);

    Debug.Log("Velocity: "+_body.velocity);
}

```

You should also apply global gravity in your project's Physics settings, and for objects that you want to fall faster, add a Constant Force component.

`ForceMode.Impulse` is similar but is affected by the rigidbody's mass. Makes it harder to tune.

# Answer
> 2 votes
Even if you dislike the built in Character Controller component(as I do), take a look at the Unity's example code for the 2D Gameplay Tutorial.

The code implements a complete 2D gameplay with moving platforms, enemies and boxes with collision, using the Character Controller.

But if you dont even want to take a look, I suggest you to minimize the use of physics and try to copy its behaviour with your own code. Depending on what kind of 2D game you are planning it may work pretty good. For instance, instead of applying force to `Rigidbody.velocity` to move your character you could mess directly with `Transform.Translate()`, which moves the object `Transform.position` based on its axis. You could determine the `forward` and `back` related to the object itself or maybe the platform or floor `Transform.up`, so you will know if its a ramp and kind of know its angle.

Also if you create some sort of speed control atributte(e.g. how long the key is pressed) you can apply it together with your direction while translating to prevent your character walking something too much inclined without some speed, much like they did on Sonic the Hedgehog for Genesis/Mega Drive.

If you choose to keep using physics I can't help you at all because I'm not so good at it, but be aware that it's a normal behaviour to go 'up a slope' slower as the body needs more force to keep up, like real life.

# Answer
> 1 votes
What you want it the built in Character Controller. By setting the `step offset` property on this component you can get a player to move up and down slopes with ease.

# Answer
> 0 votes
I suppose it is because the force is not parallel to the platform and the result ends up being lower in rise and higher in descent.

If you apply a relative force to the coordinate system

```
AddRelativeForce

```

You want to keep a maximum speed in "x" and compare it against a scalar, remember that speed is a vector and compose v.x and v.y, in flat terrain v.y is zero, but necessarily on slopes is greater than zero.

The velocity changes according to the direction of the body, and its relative v.x changes with respect to its overall v.x.

This can modify your V in a way you do not want too:

```
if (Mathf.Abs (v.x)> _ maxWalkSpeed) v.x = _maxWalkSpeed;

```

maintaining the same global V.x may seem strange to the eye. (Unwanted Accelerations)

---
Tags: unity, physics, game-mechanics
---


# Question
Title: Multiple points of gravity in GameMaker Studio 2
I'm trying to make a simple 2D prototype in GameMaker Studio 2 where there're multiple points of gravity, essentially static objects in the scene that attract the player-object based on distance and mass of the object. Does anyone know if this would be complicated to get working? I've been trying to find resources on how to do this, but so far I've not found much helpful, so if anyone has any pointers for me that would be much appreciated.

# Answer
> 1 votes
The difficulty really depends on your programming experience. If you're looking for a prefab solution I doubt you'll find one out there. Seems like a pretty straight forward coding challenge. You'll need to create an object and write some script that detects it's distance from the player and use the distance to determine how far to move the player toward the object. I suggest looking at GameMaker Studio 2's platformer sample game and using that as a jumping off point. Hope that helps, good luck!

---
Tags: 2d, physics, game-maker
---


# Question
Title: Stop displaying a camera sign in a Scene view in Unity
How can I stop displaying a camera sign in a Scene view in Unity?

I mean that white thing you see below:

# Answer
> 3 votes
In your screenshot on the grey bar, look for the button "Gizmos". You can turn those icons on or off and make them smaller and larger.

---
Tags: unity, camera, ide
---


title: Unity: Component not being serialized

text:
# Question
Title: Unity: Component not being serialized
I have a script like this:

```
public class A: MonoBehaviour {
   public bool x = false;
}

```

... and a Custom Editor like this:

```
[CustomEditor(typeof(A))]
public class A_E: Editor
{
   public override void OnInspectorGUI()
   {
      A a= target as A;
      if (a== null || a.gameObject == null) return;
      a.x = !EditorGUILayout.Toggle("x", !a.x);
   }
}

```

When I enter play mode, the property resets.

I tried fixing it by adding:

```
if(GUI.changed) EditorUtility.SetDirty(a);

```

However this only fixed it for play mode.
If I save and close the scene, it resets to the default.
Also, the scene is not set to dirty, if I make changes to the component through the custom editor.

# Answer
You'll notice the docs for SetDirty point out that this method has been replaced:

> Prior to Unity 5.3, this was the primary method of marking objects as dirty. From 5.3 onwards, with the introduction of Multi-Scene Editing, this function should no-longer be used for modifying objects in scenes. Instead, you should use Undo.RecordObject prior to making changes to the object. This will mark the object's scene as dirty and provide an undo entry in the editor.

Here's how your code would look with this pattern:

```
public override void OnInspectorGUI() {
    A a= target as A;

    if (a== null || a.gameObject == null)
         return;

    EditorGUI.BeginChangeCheck();
    bool x = !EditorGUILayout.Toggle("x", !a.x);
    if(EditorGUI.EndChangeCheck()) {
        Undo.RecordObject(target, "Changed x");
        a.x = x;
    }
}

```
> 1 votes

# Answer
Here's another solution that I ultimately went with:

```
[CustomEditor(typeof(A))]
public class A_E: Editor
{
   private SerializedProperty x;

   public OnEnable(){
      x = serializedObject.FindProperty("x");
   }

   public override void OnInspectorGUI()
   {
      serializedObject.Update();
      x.boolValue = !EditorGUILayout.Toggle("x", !x.boolValue);
      serializedObject.ApplyModifiedProperties();
    }
}

```
> 0 votes

---
Tags: unity, serialization
---


# Question
Title: How do you go about distributing resources procedurally in a game?
What I mean by resource distribution is the placement of items in the game. More specifically "minable" items in builder/resource gathering games like Factorio, Oxygen not included or/and RimWorld.

The games all place clumps of the same items around each other. For example in **Factorio** there will be fields of resources like coal, iron, copper, etc. which will spawn together in **little clusters** rather than there being single resource tiles being sprinkled around the map. See screenshot:

This is a similar behaviour in **Oxygen not included**, **similar resources** are more likely to be **next to each other** but depending on the rarity they can also be found alone as a single block. In the game there are also zones which denote what resources can spawn which appear to be preset locations and shapes as they are the same each game (with the types mixed up), but resources themselves are position procedurally. I grabbed a screenshot online and highlighted some of the resource types to make the distribution more obvious.

The **ideal answer** will show what methods would work well to reproduce "clustered resource distribution", with advantages and disadvantages of a given method. It will not necessarily have code examples but rather the rough steps/pseudocode that would have to be taken.

# Answer
The same way you do all the other procedural generation, **procedurally**.

Typically this starts with "some kind of noise". Then you'll scale and filter the noise to extract data from it.

For example, you have a 2D array of pseudo-random noise with values ranging from 0 to 1. Map this 2D array to your world, likely via x,y coordinates. For all the values greater than .95 in your 2D array, add a copper node to the world at that point. The amount of copper in the node is higher the closer the value is to 1.

For example, in this image of a terrain, the developer has used a piecewise function to determine the elevation of the terrain. i.e.

```
if value > .9: elvation = 10,
if .75 < value < .9: elevation = 8
etc.

```

For the resource example, only the highest terrain locations would be set as resource locations.

If you want your resource to be more common, instead of .95, choose .9 or some smaller number, thus increasing the area your resource covers.

Procedural maps like those in the games you reference are made up of many layers of noise. Each layer is a different scale with a different seed defining a different attribute. There will be layers for biomes, water, enemy placement, resources, etc. Some layers will reference other layers to ensure they're not violating placement rules (like resources on top of water).

All in all, it's a custom combination of rules and noise the create a complete map.
> 5 votes

---
Tags: procedural-generation
---


# Question
Title: DirectX11 - Color Interpolation Along Quad Diagonal
Imagine that we have a vertex structure that looks like this:

```
struct Vertex
{
    XMFLOAT3 position;
    XMFLOAT4 color;
};

```

The vertex shader looks like this:

```
cbuffer MatrixBuffer
{
    matrix world;
    matrix view;
    matrix projection;
};

struct VertexInput
{
    float4 position : POSITION;
    float4 color    : COLOR;
};

struct PixelInput
{
    float4 position : SV_POSITION;
    float4 color    : COLOR;
};

PixelInput main(VertexInput input)
{
    PixelInput output;

    input.position.w = 1.0f;

    output.position = mul(input.position,  world);
    output.position = mul(output.position, view);
    output.position = mul(output.position, projection);

    output.color = input.color;

    return output;
}

```

And the pixel shader looks like this:

```
struct PixelInput
{
    float4 position : SV_POSITION;
    float4 color    : COLOR;
};

float4 main(PixelInput input) : SV_TARGET
{
    return input.color;
}

```

Now let's create a quad consisting of 2 triangles and the vertices A, B, C and D:

```
// Vertex A.
vertices[0].position = XMFLOAT3(-1.0f,  1.0f,  0.0f);
vertices[0].color    = XMFLOAT4( 0.5f,  0.5f,  0.5f,  1.0f);

// Vertex B.
vertices[1].position = XMFLOAT3( 1.0f,  1.0f,  0.0f);
vertices[1].color    = XMFLOAT4( 0.5f,  0.5f,  0.5f,  1.0f);

// Vertex C.
vertices[2].position = XMFLOAT3(-1.0f, -1.0f,  0.0f);
vertices[2].color    = XMFLOAT4( 0.5f,  0.5f,  0.5f,  1.0f);

// Vertex D.
vertices[3].position = XMFLOAT3( 1.0f, -1.0f,  0.0f);
vertices[3].color    = XMFLOAT4( 0.5f,  0.5f,  0.5f,  1.0f);

// 1st triangle.
indices[0] = 0; // Vertex A.
indices[1] = 3; // Vertex D.
indices[2] = 2; // Vertex C.

// 2nd triangle.
indices[3] = 0; // Vertex A.
indices[4] = 1; // Vertex B.
indices[5] = 3; // Vertex D.

```

This will result in a grey quad as shown in the image below. I've outlined the edges in red color to better illustrate the triangles:

Now imagine that we’d want our quad to have a different color in vertex A:

```
// Vertex A.
vertices[0].position = XMFLOAT3(-1.0f, 1.0f, 0.0f);
vertices[0].color    = XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f);

```

That works as expected since there’s now an interpolation between the black color in vertex A and the grey color in vertices B, C and D. Let’s revert the previus changes and instead change the color of vertex C:

```
// Vertex C.
vertices[2].position = XMFLOAT3(-1.0f, -1.0f, 0.0f);
vertices[2].color    = XMFLOAT4( 0.0f,  0.0f, 0.0f, 1.0f);

```

As you can see, the interpolation is only done half of the way across the first triangle and not across the entire quad. This is because there's no edge between vertex C and vertex B.

Which brings us to my question:

**I want the interpolation to go across the entire quad and not only across the triangle. So regardless of which vertex we decide to change the color of, the color interpolation should always go across the entire quad. Is there any efficient way of achieving this without adding more vertices and triangles?**

An illustration of what I'm trying to achieve is shown in the image below:

---

## Background

This is just a very brief explanation of the problems background in case that would make it easier for you to understand the problems roots and maybe help you with finding a better solution to the problem.

I'm trying to texture a terrain mesh in DirectX11. It's working, but I'm a bit unsatisfied with the result. When changing the terrain texture of a single vertex, the interpolation with the other vertices results in a hexagon shape instead of a squared shape:

As the red arrows illustrate, I'd like the texture to be interpolated all the way into the corners of the quads.

# Answer
> 2 votes
You need per-fragment color interpolation rather than per vertex color interpolation. If you write the interpolation yourself in the fragment shader, you can make it work any way you'd like.

Unfortunately, I don't know Direct X or HLSL, but here's what it would look like in glsl. I imagine it's similar in HLSL. (Also, this is off the top of my head, untested.) Here I'm assuming that your texture coordinates go from 0-1 in both directions.

```
uniform vec2 chosenCornerCoord;

void main()
{
    vec2 diff = gl_TexCoord[0].xy - chosenCornerCoord;
    float dist = sqrt(dot(diff, diff));
    gl_FragColor = vec4(dist, dist, dist, 1.0);
}

```

This will actually give you a euclidean distance from the chosen corner which will result in a rounded falloff. You could use a manhattan (taxi) metric for the more square falloff you're seeing in your example.

In the above, `gl_TexCoord[0]` is the texture coordinate for the current fragment. `chosenCornerCoord` is the texture coordinate of the corner you want to measure the distance from. (Again, assuming texture coords from 0 to 1.)

# Answer
> 0 votes
Probably not the thing you want to hear, but have you considered using a reference blend texture rather than what you are constrained by at the moment via the current interpolation constrained by geometry.

---
Tags: c++, directx, directx11, fragment-shader, terrain-rendering
---


# Question
Title: Which Entities should be in my Pooling System?
Let's suppose that I'm designing a Tanks Battle Game, there will be a lot of projectiles and Tanks. Every Tank is composed with a Body, multiple Weapons such as Machine Guns, Missile Launchers, etc and different Shield Systems. I want to generate the Tanks at run-time and I will need to create and destroy them frequently. Should I add every type of Weapon, Shield, etc.. to my Pool System and recycle them when a Tank is destroyed, and later reuse them to assemble a new "Randomly" generated tank? Is this realistic? or should I just instantiate the Body, Weapons and Shields and don't use the Pool System for it? Do you have some tips for organize the Pool System?

I was looking for a advanced pooling system and I just got basic theory and examples. Any reference, suggestions, corrections or advice will be very grateful.

# Answer
> 0 votes
Pooling is generally useful to eliminate the costs of creating and destroying objects of the same type over and over again, whatever those costs may be in your language.

So if you're going to create and destroy the tanks frequently, then yes, they may be a good candidate for pooling. If the creation and destruction of the tanks requires you to create and destroy related objects (such as the weapons on those tanks), they *also* may be a candidate for pooling.

Profiling your actual use case will help you find the places where pooling actually brings you significant wins versus places where it's just hedging against future performance issues that may not materialize.

---
Tags: architecture, design-patterns
---


# Question
Title: How to correctly setup latest LWJGL libraries to Eclipse?
A year ago, I understood how to setup an LWJGL project in Eclipse IDE. Now LWJGL has a lot of changes including a different file structure. I downloaded the latest release, LWJGL **3.1.0** Build 40 from the official site.

There's also a page explaining how to get started, but it does not help me to set it up in Eclipse. When I extract the downloaded `.zip` file, I only get `.jar` files (and `.txt` licences). I see nowadays there are no `.dll` natives for a specific operating system.

Instead of that, I see jars like `lwjgl-glfw-natives-windows.jar`. I expect these are now the files that were previously `.dll` files.

Can someone explain to me how to set it all up correctly?

# Answer
> 2 votes
You can create gradle or maven project and add dependencies which you can generate on lwjgl download page.

Another way - you can download jar

Create simple Java project in eclipse, create folder in project called for example `lib` and put all jars from archive to this folder

After that go to Project -\> Properties -\> Java Build Path -\> Libraries -\> Add JARs... and select all jars from this folder.

Create class HelloWorld from Get started guide and run it. Done.

# Answer
> 2 votes
I've had to do this multiple times as of recent: here's my method.

First, head over to the LWJGL homepage, and click on the DOWNLOAD tab up at the top.

After that, click "Customize LWJGL 3"

From there, select "Release", and click on the modules, modes, natives and presets you want. I usually get the ZIP Bundle with Windows natives and everything included, along with JOML. Hit "DOWNLOAD ZIP" at the bottom, and extract it to anywhere you please.

Now, open up your project in Eclipse, and create a new folder called "lib" or "library". From there, get your extracted JARs from your extracted ZIP file, and put 'em in.

From there, click on your project and hit Alt+Enter to bring up the properties menu. Inside there, click on Java Build Path, then "Add JARs..."

Click on your lib or library file, and select the ones you need, then hit OK.

Congratulations! You've now set up LWJGL 3 in Eclipse! Now it's time to create your src directory and start coding.

As for the natives that used to be `.dll` files back in LWJGL 2, they've changed them all to `.jar` files (yeah, it threw me off, too when I made the switch).

(If I didn't explain it well enough, here's the tutorial I used)

---
Tags: opengl, java, lwjgl, eclipse
---


# Question
Title: Accessing vertex Input in surf directly without vert's out parameter In Tessellation Shader
I can get the vertex Input in vertex shader as follows:

```
   o.worldPos = v.vertex.xyz;

```

But how do I get the worldPos directly without filling the out parameter in the vert function. Asking this because the shader is a DX11 Tessellation one and out parameter in vert function is not available at all.

basically I want Initialize my Input shader and pass It to surface shader In vertex shader.I can do It but It's different In Tessellation shader so I need to Accessing vertex position in surf directly without vert's out parameter.

```
Shader "Tessellation Sample" {
        Properties {
            _EdgeLength ("Edge length", Range(2,50)) = 15
            _MainTex ("Base (RGB)", 2D) = "white" {}
            _DispTex ("Disp Texture", 2D) = "gray" {}
            _NormalMap ("Normalmap", 2D) = "bump" {}
            _Displacement ("Displacement", Range(0, 1.0)) = 0.3
            _Color ("Color", color) = (1,1,1,0)
            _SpecColor ("Spec color", color) = (0.5,0.5,0.5,0.5)
        }
        SubShader {
            Tags { "RenderType"="Opaque" }
            LOD 300

            CGPROGRAM
            #pragma surface surf BlinnPhong addshadow fullforwardshadows vertex:disp tessellate:tessEdge nolightmap
            #pragma target 4.6
            #include "Tessellation.cginc"

            float _EdgeLength;

            float4 tessEdge (appdata_full v0, appdata_full v1, appdata_full v2)
            {
                return UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, _EdgeLength);
            }

            float _Displacement;

            struct Input {
                float4 position  : POSITION;
                float3 worldPos  : TEXCOORD2;   // Used to calculate the texture UVs and world view vector
                float4 proj0     : TEXCOORD3;   // Used for depth and reflection textures
                float4 proj1     : TEXCOORD4;   // Used for the refraction texture
            };

            void disp (inout appdata_full v, out Input o){
            UNITY_INITIALIZE_OUTPUT(Input,o);
            o.worldPos = v.vertex.xyz;
            o.position = UnityObjectToClipPos(v.vertex);
            o.proj0 = ComputeScreenPos(o.position);
            COMPUTE_EYEDEPTH(o.proj0.z);

            o.proj1 = o.proj0;
            #if UNITY_UV_STARTS_AT_TOP
            o.proj1.y = (o.position.w - o.position.y) * 0.5;
            #endif
            }

            sampler2D _MainTex;
            sampler2D _NormalMap;
            fixed4 _Color;

            void surf (Input IN, inout SurfaceOutput o) {
                o.Albedo = float3(0,0,0);
            }
            ENDCG
        }
        FallBack "Diffuse"
    }

```

but I have error:

```
Shader error in 'Tessellation Sample': 'disp': no matching 1 parameter function at line 173 (on d3d11)

```

# Answer
> 1 votes
It's a bug

For a workaround, have a look at Post #13 The idea behind this is to use unused vertex attributes to pass your custom data through.

---
Tags: unity, tessellation, shaderlab
---


# Question
Title: Prefabs were modified even it doesn't updated when commit
Me and my co-workers uses Git for saving the developing game. But sometimes, some co-worker push the commit, it contains modified prefab that he never did.

Prefabs are binary files so I can't see what is changed until pull. The big problem is that those prefabs are already used other scenes so updating it's property might be cause unexpected behaviour.

Also if I do something work with one of that prefabs, that could be overwritten(or maybe not. git refuse the commit because of conflicts).

Anyway, my co-worker said he didn't touched any property of prefabs, even he didn't clicked it at all, but it still modified from his computer.

In this case, what makes those prefabs modified? How do I avoid those weird situation?

# Answer
> 1 votes
We used to get this a lot with materials.

We tracked it down to one of our dynamic instantiation scripts, which took a shared base material, set the colour/texture/parameters to instance-specific values, *then* assigned an instance of the material to a renderer.

This meant the base material in our assets folder was constantly getting small changes made whenever we ran the game, and even though they happened in play mode, since it's an asset file, they're not undone when exiting back to edit mode. So they got saved to disc and Unity decided the asset had been modified and added it to the change list. But we didn't see any visible changes in-game, because the changes were only to parameters that we overwrite before use anyway, so it stayed mysterious for a long time.

Taking care to instantiate a copy of the asset first, *then* customize its instance-specific data stopped the phantom check-ins.

If it helps, you can change your asset serialization mode to "Force Text" to investigate what changes Unity thinks are being made, which might help track down their source.

---
Tags: unity, git
---


# Question
Title: Unity - GameObject jumps to wrong point at start
In Unity, I have this problem where the Game Object this script is attached to jumps to Z position 0 as soon as the game runs. In the Editor, I have the Game Object set as Z position -50. I want startPos to read this position (-50) and use it when newPos is updated.

Why does startPos get updated immediately to 0?

```
using UnityEngine;

public class MoveOutScript : MonoBehaviour {

    public float speed = 10f;
    float startPos;
    Vector3 newPos;
    float changePerSecond2;

    public void Start()
    {
        startPos = transform.position.z;
        changePerSecond = speed * Time.deltaTime;
    }

    public void Update()
    {
        #region Move sprite away steadily

        newPos.z += changePerSecond;
        newPos.z = Mathf.Clamp(newPos.z, startPos, 15f);
        transform.localPosition = newPos;

        #endregion
    }
}

```

# Answer
> 1 votes
It is probably because you are updating the *local* position, even though you get your start position from the *absolute* position. If its parent is not at the origin but instead at (0, 0, 50), a local position of (0, 0, -50) would put it right at the origin.

Perhaps having `transform.position = newPos` instead would fix it.

# Answer
> 0 votes
It was as simple as me not declaring newPos to equal startPos in the Start() method. newPos was defaulting to 0, which is why it always started from that position. Now, it starts at startPos.

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


# Question
Title: "Breakout" script fails to trigger win after destroying the last brick
The behavior I want is that when all the bricks are destroyed, the last brick's `OnCollisionEnter2D` handler calls `SimulateWin()`, triggering the next level.

For some reason `SimulateWin()` is never called.

```
using UnityEngine;
using System.Collections;

public class Brick : MonoBehaviour {

    public static int brickCount = 0;
    public int maxHits;
    public int timesHit;
    private LevelManager levelmanager;

    void Start ()
    {
        timesHit = 0;
        levelmanager = GameObject.FindObjectOfType<LevelManager>();
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        timesHit++;
        Debug.Log("Collision happened with " + col.gameObject.name);

        if(timesHit >= maxHits)
            Destroy(gameObject);

        if(GameObject.FindObjectOfType<Brick>() == null)//Not entering this if
            SimulateWin();//this is never called
    }

    void SimulateWin()//This is the function that is supposed to be called when all the bricks are destroyed.
    {
        levelmanager.LoadNextLevel();
    }

}

```

# Answer
Two things to know about Unity's various Find methods:

1. As others have pointed out, Unity's Find methods have to search through potentially many objects in your scene to find the one(s) meeting your criteria, and that can be needlessly slow - especially in large complex scenes.

* Switching to FindObject**s**OfType as suggested in another answer can technically be even worse, because instead of stopping the search after finding the first one, Unity has to keep looking to find more, and has to allocate memory for an array to return them in.
    * Of course, for a small game prototype like it sounds like you're making, this is unlikely to be a big deal. You'll find experienced Unity devs like us get hung up about it more as a matter of maintaining good code hygiene and avoiding creeping problems in the future, rather than any immediate crisis. ;)
2. Unity's Find methods will find even an object that was `Destroy()`ed this frame, because `Destroy` takes effect *at the end* of the frame, just before rendering.

* So your `FindObjectOfType<Brick>()` call still finds that last brick, because we're checking in the same frame that we destroyed it.
    * Calling the same Find method from another object, as suggested in another answer, won't get around this if you're still checking in the same frame.
    * Trying to hack around this gets weird and ugly. That's a good sign there's a better solution available.

---

What I'd recommend here is a simple **counter**.

* When we add a Brick to our scene, we'll increment the counter.
* When it's destroyed, we'll decrement it.
* Then we can query how many are left at any time just by checking the value of a variable - no searching required!

In fact, you even have the counter variable already waiting there in your code - you're just not using it yet. :)

```
public class Brick : MonoBehaviour {

    // Here's our counter variable that was there all along.
    // The "static" means it's shared between all Bricks.
    public static int brickCount = 0;
    //...
    void Start ()
    {
        // Add one to our brick count for this new brick.
        brickCount++;

        timesHit = 0;

        // Most bricks never actually use the LevelManager,
        // so let's skip doing that here. Just find it when you win.
        //levelmanager = GameObject.FindObjectOfType<LevelManager>();
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        timesHit++;

        if(timesHit >= maxHits) {
            brickCount--;
            Destroy(gameObject);
        }

        if(brickCount == 0)
            SimulateWin();
    }

    // ...
}

```

The counter has some side benefits too. Now any other script in your scene can query `Brick.brickCount` to find out how many bricks are left, and do things like...

* Display a remaining count in the game's UI
* Play different sounds to build up to a climax as you close in on the final few bricks
* Add a "Time Attack" game mode where you're scored on how many bricks you're able to break in a limited time
* Change the spawning rate of bonuses/power-ups, or always spawn a particular item when you cross the halfway mark...

And all of this is practically free, because you're just reading the value of an integer. :)

(Though I would recommend making the variable private and exposing a Getter for it, so outside scripts don't unintentionally mess with our count...)
> 1 votes

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


title: What does this statement mean?

text:
# Question
Title: What does this statement mean?
I am new to Unity as well as programming, I came across this statement and couldn't comprehend what it meant,

```
var result = numX != lastnumX || numY != lastnumY;

```

Can anyone explain how this works?

# Answer
Basically this should be read as:

var result = (numX ***not equal to*** lastnumX) ***or*** (numY ***not equal to*** lastnumY);

the result is boolean value, i.e. either True or False.

P.S. while it's certainly possible to ask such questions, this question shows that you lack pretty basics of the programming, you should get a C# programming book/course to familiarise yourself with it before you continue.
> 1 votes

# Answer
* `!=` means "does not equal"

So `numX != lastnumX` evaluates to the `boolean` value `true` if `numX` is different from `lastnumX`, or `false` if both variables are the same.

The same applies for `numY != lastnumY`
* `||` (double pipe) is a "logical or" operator - it checks whether *at least one* of the expressions on either side of it is `true`

First it evaluates the expression on the left, and if it's `true` then the result is `true`

(It does this without even checking the expression on the right - this is called "short circuiting" and it's useful to bail out of expensive or invalid checks if an earlier check tells you everything you need to know)

If the expression on the left is `false`, then it checks the value of the expression on the right, returning `true` if it's `true` and `false` otherwise.

So inferring from the variable names, `var result` is a `boolean` variable that holds the value `true` if either `numX` or `numY` have changed values since "last time," and `false` if both numbers have stayed the same.
> 1 votes

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


# Question
Title: Delay/Pause game while displaying countdown 3,2,1 go
I have already a running script of countdown and it works fine , the problem is that I want to pause or delay the game while the countdown is displaying, the moment countdown finished the player is already dead. Here is my code

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

public class jb : MonoBehaviour {
    private string countdown = "";
    private bool showCountdown = false;
    public AudioSource noise1;
    public AudioSource noise2;
    public Sprite sprite2;
    public Vector2 jump = new Vector2 (0,300);
    private SpriteRenderer spriteRenderer;
    void Start () {
        //GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
        StartCoroutine(getReady());

        spriteRenderer = GetComponent<SpriteRenderer>();
        noise1.GetComponent<AudioSource>().Play();

    }

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

        if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
           Vector2 touchPosition = Input.GetTouch(0).position;
            GetComponent<Rigidbody2D>().AddForce(jump);
            //noise1.GetComponent<AudioSource>().Play();
        }

        Vector2 screen_position = Camera.main.WorldToScreenPoint (transform.position);
        if(screen_position.y > Screen.height || screen_position.y < 0)
        {
            noise1.GetComponent<AudioSource>().Stop();
            noise2.GetComponent<AudioSource>().Play();
            StartCoroutine(Die());
        }

    }

    void OnCollisionEnter2D(Collision2D det)
    {
        noise1.GetComponent<AudioSource>().Stop();
        noise2.GetComponent<AudioSource>().Play();
        StartCoroutine(Die());

    }

    IEnumerator Die(){
        PlayerPrefs.SetString( "previousLevel", SceneManager.GetActiveScene().name );
        spriteRenderer.sprite = sprite2;
        yield return new WaitForSeconds (2);
        SceneManager.LoadScene("score");
     }

    IEnumerator getReady()
    {
        showCountdown = true;

        countdown = "3";
        yield return new WaitForSeconds (1);

        countdown = "2";
        yield return new WaitForSeconds (1);

        countdown = "1";
        yield return new WaitForSeconds (1);

        countdown = "GO";
        yield return new WaitForSeconds (1);

        showCountdown = true;
        countdown = "";
    }

    void OnGUI ()
    {
        if (showCountdown)
        {
            GUI.color = Color.red;
            GUI.Box ( new Rect (Screen.width / 2 - 100, 50, 200, 175), "GET READY");

            // display countdown
            GUI.color = Color.white;
            GUI.Box (new Rect (Screen.width / 2 - 90, 75, 180, 140), countdown);
        }
    }
}

```

what can I do to pause the game? I tried invoke (by creating another function and copying everything over there) in update call but it didn't work.

# Answer
I've added a simple boolean value to your code: `started`.

At the start, it's false so `Update()` doesn't update the game. When the countdown finishes, we set it to true so `Update()` can update.

Also, you need to make your player's `Rigidbody2D` unable to move by making it `kinematic` in the `Start()` method:

`GetComponent<Rigidbody2D>().isKinematic = true;`

and then set it to `false` after the countdown :)

```
public class jb : MonoBehaviour {
    private string countdown = "";
    private bool showCountdown = false;
    public AudioSource noise1;
    public AudioSource noise2;
    public Sprite sprite2;
    public Vector2 jump = new Vector2 (0,300);
    private SpriteRenderer spriteRenderer;

    bool started = false;

    void Start () {
        //GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
        StartCoroutine(getReady());

        spriteRenderer = GetComponent<SpriteRenderer>();
        noise1.GetComponent<AudioSource>().Play();

        GetComponent<Rigidbody2D>().isKinematic = true;
    }

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

        if(!started) return;

        if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
           Vector2 touchPosition = Input.GetTouch(0).position;
            GetComponent<Rigidbody2D>().AddForce(jump);
            //noise1.GetComponent<AudioSource>().Play();
        }

        Vector2 screen_position = Camera.main.WorldToScreenPoint (transform.position);
        if(screen_position.y > Screen.height || screen_position.y < 0)
        {
            noise1.GetComponent<AudioSource>().Stop();
            noise2.GetComponent<AudioSource>().Play();
            StartCoroutine(Die());
        }

    }

    void OnCollisionEnter2D(Collision2D det)
    {
        noise1.GetComponent<AudioSource>().Stop();
        noise2.GetComponent<AudioSource>().Play();
        StartCoroutine(Die());

    }

    IEnumerator Die(){
        PlayerPrefs.SetString( "previousLevel", SceneManager.GetActiveScene().name );
        spriteRenderer.sprite = sprite2;
        yield return new WaitForSeconds (2);
        SceneManager.LoadScene("score");
     }

    IEnumerator getReady()
    {
        showCountdown = true;

        countdown = "3";
        yield return new WaitForSeconds (1);

        countdown = "2";
        yield return new WaitForSeconds (1);

        countdown = "1";
        yield return new WaitForSeconds (1);

        countdown = "GO";
        yield return new WaitForSeconds (1);

        showCountdown = true;
        countdown = "";

        started = true;
        GetComponent<Rigidbody2D>().isKinematic = false;
    }

    void OnGUI ()
    {
        if (showCountdown)
        {
            GUI.color = Color.red;
            GUI.Box ( new Rect (Screen.width / 2 - 100, 50, 200, 175), "GET READY");

            // display countdown
            GUI.color = Color.white;
            GUI.Box (new Rect (Screen.width / 2 - 90, 75, 180, 140), countdown);
        }
    }
}

```
> 0 votes

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


# Question
Title: Why does this raycast code give me a NullReferenceException?
The Error in the code is NullReferenceException: Object reference not set to an instance of an object for if (hitxx.collider.tag == "soldier") Please help! Thanks in advance

```
 void Update () {
            Physics.Raycast (eyeenemy.transform.position, (eyeenemyfront.transform.position - eyeenemy.transform.position) * 20,out hitxx);

            Debug.DrawRay (eyeenemy.transform.position, (eyeenemyfront.transform.position - eyeenemy.transform.position) * 20,Color.green);
            if (hitxx.collider.tag == "soldier") {
                gameObject.transform.LookAt (soldier.transform.position);
                Debug.Log ("chuchu");
            }

```

# Answer
> 1 votes
Your `hitxx`, of type `RaycastHit`, is only initialized by `Physics.Raycast()` if it actually hits something. Otherwise it will remain unchanged since the last hit or will be null if nothing has been hit in the past. You are failing to handle the condition in which nothing is hit. When you get to checking the tag, it is trying to access a collider on a null reference.

`Physics.Raycast()` actually returns a bool representing whether something was hit. You could use that in a condition so be sure that `hitxx` is not null.

```
bool isHit = Physics.Raycast (eyeenemy.transform.position,
        (eyeenemyfront.transform.position - eyeenemy.transform.position) * 20,out hitxx);
...
//will not attempt to access hitxx if isHit is false
if (isHit && hitxx.collider.tag == "soldier") {
    ...
}

```

---
Tags: unity, c#, android, raycasting
---


# Question
Title: How can I abort the closing of a dialog in libgdx?
```
Dialog dialog = new Dialog("Warning", skin, "dialog") {
    public void result(Object obj) {
        System.out.println("result "+obj);
        if(obj == true) {
            >> abort the dialog closing ? <<
        }
    }
};
dialog.text("Info?");
dialog.button("Yes", true);
dialog.button("No", false);
dialog.key(Keys.Enter, true);
dialog.show();

```

how to abort the closing of the dialog?

# Answer
The documentation notes that when the `result` method is called, the dialog will be hidden unless `cancel()` is called.

So you'll want to invoke `dialog.cancel()` within your result callback somewhere.
> 2 votes

---
Tags: libgdx
---