What is the proper way to instantiate multiple objects from a script while in the editor in Unity? I would like to, for example, be able to spawn a wall of stacked boxes and be able to play with the number of boxes in each dimension in the editor (previously I would be instantiating these at runtime, but it is annoying to not be able to see these in the editor). Currently I am using a bit of a work around, I am using the OnValidate method to achieve this, but its a bit of a bodge and my instantiated items do not spawn in play mode, I get the following error on play MissingReferenceException The object of type 'Lattice' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. Lattice. lt OnValidate gt b 8 0 () (at Assets Lattice.cs 22) UnityEditor.EditorApplication.Internal CallDelayFunctions () (at home bokken buildslave unity build Editor Mono EditorApplication.cs 346) Here is the script I am currently using public class Lattice MonoBehaviour public int nX 1, nY 1, nZ 1 public float offsetX 1, offsetY 1, offsetZ 1 public GameObject item Validate called only in editor and only on variable change void OnValidate() Clean() remove old items UnityEditor.EditorApplication.delayCall () gt spawnBox3Grid(item, transform, nX, nY, nZ, offsetX, offsetY, offsetZ) void Clean() foreach(Transform childT in transform) UnityEditor.EditorApplication.delayCall () gt Debug.Log(childT.gameObject.name) DestroyImmediate(childT.gameObject) void spawnBox2Grid(GameObject obj, Transform parent, Vector3 startingPos, int nItemsY, int nItemsZ, float zOff 1.0f, float yOff 1.0f, int k 0) Vector3 boxPos startingPos new Vector3(0, yOff 2, zOff nItemsZ 2) Vector3 zOffset new Vector3( 0, 0, zOff) Vector3 yOffset new Vector3( 0, yOff, 0) for (int j 0 j lt nItemsY j ) for (int i 0 i lt nItemsZ i ) GameObject instance Instantiate(obj, boxPos, Quaternion.identity, parent) instance.name string.Format( quot obj 0 1 2 quot , i, j, k) instance.transform.localPosition boxPos instance.transform.localRotation Quaternion.identity boxPos zOffset boxPos nItemsZ zOffset boxPos yOffset void spawnBox3Grid(GameObject obj, Transform parent, int nItemsX, int nItemsY, int nItemsZ, float xOff 1.0f, float yOff 1.0f, float zOff 1.0f) Vector3 xOffset new Vector3( xOff,0, 0) Vector3 boxPos new Vector3( xOff nItemsX 2,0,0) for (int k 0 k lt nItemsX k ) spawnBox2Grid(obj, parent, boxPos,nItemsY,nItemsZ, yOff, zOff, k) boxPos xOffset This YouTube video is probably closer to what I want, but I don't entirely understand it and was hoping there was a simpler way. Edit Some extra context Delaying the DestroyImmediately calls seems to be the only way to delete objects from inside OnValidate and if I don't delay the Instantiate calls I get SendMessage cannot be called during Awake, CheckConsistency, or OnValidate. Edit 2 I guess I can use this code for previewing in the editor then use a scriptable object to store the parameters of my Lattice objects and then re instantiate things at runtime? But that error that I'm getting is it trying to run OnValidate just before play? (When presumably, the things I've instantiated aren't stored permanently so the lattice object is lost?) There has got to be a cleaner way of doing this...


Should I combine multiple tiles of terrain as one mesh in Unity3D? I have a tiled terrain, generated by multiple noise algorithms. Currently, each tile is it's own GameObject, that has a handler for an OnMouseOver event. The area that is loaded at a time consists of 9 chunks that each contain 4096 tiles. This totals to 36864 tiles that are loaded at a time. On top of this, there are actual objects on top of these tiles. Is there any considerable performance difference if I were to combine some of these tiles into a single GameObject and mesh?


Question about coding rarity and non MonoBehaviour referencing I have a non MonoBehaviour script called Item which contains two classes. public class Item public string itemName public string itemRarity public Item(string newItemName) itemName newItemName and public class ItemRandomizer List lt Item gt itemContainer new List lt Item gt () public void AddItem(Item item, int amount) for (int i 0 i lt amount i ) itemContainer.Add(item) public Item GetRandomItem() int index Random.Range(0, itemContainer.Count) want to return item combined with rarity return itemContainer index I want GetRandomItem to not only return a random item "type", e.g., gloves, contained in the itemContainer list, but also combine it with a rarity (common, rare, legendary) and return that if possible. How can I code this functionality in a flexible way so that two base items with the same drop chance can have varying drop chances when it comes to their rare versions? Swords and axes have the same drop chance, but a rare sword might be rarer than a rare axe. I'd like to maintain that kind of flexibility. Also, if I make public string itemRarity a property of the Item class, but I want to set the rarity tier in GetRandomItem() in the ItemRandomizer class, how should I do that? Thus far, I've almost exclusively used MonoBehaviour classes so any pointers are appreciated.


How can it be that if I click on rawimage it's getting the right file name from the hard disk ? I don't understand it In this script once only I'm getting the all the files from the hard disk type png images. using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) string fileName imagesToLoad i MouseHover.savedGameFName fileName byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName go.GetComponent lt RawImage gt ().texture thisTexture Update is called once per frame void Update() At this line I'm doing reference from another script to a public static variable MouseHover.savedGameFName fileName Then in the MoueHover script that I'm using it calling it from each raw image event trigger I'm using also the mouse button down using System.Collections using System.Collections.Generic using System.Drawing using System.Drawing.Imaging using System.IO using UnityEngine using UnityEngine.EventSystems using UnityEngine.UI public class MouseHover MonoBehaviour public SaveLoad saveLoad public SceneFader sceneFader public RawImagePixelsChange rawImagePixelsChange public static string savedGameFName public static string folder public static bool loadingwithfolder false private bool loadGame false public void OnHover() Debug.Log( quot Enter quot ) rawImagePixelsChange.modifyPixels(0.3f) PlaySoundEffect() loadGame true public void OnHoverExit() Debug.Log( quot Exit quot ) rawImagePixelsChange.restorePixels() loadGame false private void Update() if(loadGame) if (Input.GetMouseButtonDown(0)) MenuController.LoadSceneForSavedGame false loadingwithfolder true folder Path.GetDirectoryName(savedGameFName) StartCoroutine(sceneFader.FadeAndLoadScene(SceneFader.FadeDirection.In, quot Game quot )) loadGame false private void PlaySoundEffect() transform.GetComponent lt AudioSource gt ().Play() At this line if (Input.GetMouseButtonDown(0)) After clicking the mouse left button inside I'm using a break point on one of the lines and I see that the variable savedGameFName contains the correct clicked raw image full directory with the file name, for example d screenshots screen 1920x1080 2021 01 26 18 56 46.png But how does it know to assign to the variable savedGameFName the correct file name of the clicked raw image? It's not a list or something, it's just public static string variable. and the only other using is in the first script when running the game once first time. I don't understand it. It's working fine!!! but I don't understand how.


Unity 3D C Shifting beetween worlds? Let's say I want to replicate Planeshifting from Legacy of Kain Soul Reaver in Unity. There are 2 realms Spectral realm and Material realm. The Spectral realm is based on the Material realm, only has the geometry distorted and certain objects fade out become non interactive. In Soul Reaver, it is used as means to go to areas where you normally wouldn't be able to in Material (distorting geometry), to use other powers (such as going through grates). My question is Is it even possible at all to implement this in Unity 3D? (I would need the Scene(level) or the objects to have 2 states somehow that I could switch beetween distort to real time.)


How can I use different fonts for different objects in Unity? In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object. In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font. But, then it changes the font on the other three objects as well. I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects?


Animations in Unity are not working properly I've done a few animations in Blender for my 3D character but the problem is, that they look different in Unity. It seems like the eyes are moving too much. I tried to change many things in import like rig etc. but nothing helped at all. Here are screenshots Wrong animation Good animation


Moving large group of units 1 by 1 takes too long, how can I improve this? I use use Unity's own NavMesh AI system and I think it works pretty well. The only problem I have is that when I move large groups of units, they will find a path one by one, but it takes a really long time as you can see in the video https gfycat.com blankhalfdartfrog To set destinations I use this public bool SetDestination(Vector3 point) if (SamplePosition(point)) agent.SetDestination(point) return true return false I know I could wait until they all have pathPending false, but that would mean the entire group moves with a huge delay. Is there some way I can improve or fix this issue? Edit It is quite simple to recreate (if you have some basic knowledge on Unity NavMesh) simply create a "click to move" script that moves a List of units to where you clicked using the code above (just fill the list in Start on each unit). Put down a few obstacles and you're done.


can't make my unity character move so I'm starting with Unity , I followed the john lemon tutorial , and I wanted to apply what I learn on a model on my own coming from blender. Everythings works , animation , rotation , but not translation . For some reasons my character doesn't move at all . It might have to do something with root motion since I have apply root motion in grey with written just after "handled by script" . Not sure what to do .. I found something about character in place, I think I'm in this case but I'm not sure how to use it in my script .. https docs.unity3d.com Manual ScriptingRootMotion.html If you ask I'll give you my project . EDIT ok so I made some advances void OnAnimatorMove() m Rigidbody.MovePosition(m Rigidbody.position m Movement m Animator.deltaPosition.magnitude 10000) m Rigidbody.MoveRotation(m Rotation) Debug.Log("m Animator.deltaPosition.magnitude " m Animator.deltaPosition.magnitude) m Animator.deltaPosition.magnitude is actually always equal to 0 , explaining why my charachter doesn't translate but why is it always equal to zero ?


Populate triangles array when you already have sorted vertices array Input is a Vector3 of verticies. Length is unknown, it could be anything above 2 so these vertices form all kinds of multifaceted shapes with 3 being a triangle and 6 hexagon ish. Poor example to visualize vertices Vector3(..), Vector3(..), Vector3(..), Vector3(..), Vector3(..) Coordinates in that array are ordered counterclockwise. I also have the coordinates of center point that these verticies form (look at illustration below) it doesn't have to be used but if it helps.. Few examples of which shapes can occur and which cannot Now I need to build meshes out of them. For each shape I need Vertices array (which I already have, nicely ordered) Triangles array 3 indices (from vertices array) per triangle until all vertices are covered How to populate triangles array with these relatively easy shapes where each vertex has "direct line of sight" to every other vertices? Number of vertices is unknown of course.


New clients don't see objects spawned before they connect I'm making a game with UNet where the server must create some objects when he connects to the game, and all clients play with these objects that the server has created. A server connects to the game In his start method he calls a function CmdbuildEverything to spawn some objects to the game. A local player connects to the game. The local player should be able to see the objects that the server player has created. The code public class GameScript NetworkBehaviour void Start() if(base.isServer) CmdbuildEverything() Command void CmdbuildEverything() GameObject ob1 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 0, 1), Quaternion.identity) GameObject ob2 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 1, 0), Quaternion.identity) GameObject ob3 (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(1, 0, 0), Quaternion.identity) NetworkServer.Spawn(ob1) NetworkServer.Spawn(ob2) NetworkServer.Spawn(ob3) The problem is that the objects are created only on the server player and don't appear on the clients payers. How can I solve that?


Textures in Unity3D appear with lower quality than in Photoshop I made game assets that look great in Photoshop, but they look like crap when I import then into Unity and run the game. Why?


Objects stick together on Collision I have a ball which has CircleCollider2D attached to it. It is also rigidbody. When it lands on a platform, it jumps . The platform is static, with Edge Collider attached. It also has a platform effector attached with quot Use One Way quot selected. Most of the times it works fine, but some times, the ball lands on the platform and instead of bouncing, just sits on the platform. When ball lands on the platform, following code is executed rb.AddForce(upForce, ForceMode2D.Impulse) upForce is Vector2(4,10) image shown below Why is this happening?


Rotation smoothing with Slerp snaps to center when switching between different destination vectors I'm making a 3D space shooter in Unity (think Star Fox). The ship, when I move it around the map, should rotate slightly (smoothly) in the direction I'm controlling it. I have smoothness mostly working. When I press an arrow key, the ship banks in that direction, and when I release it, it smoothly returns to the default rotation. However, if I quickly change the direction it's rotating before it has the chance to get back to the default rotation, instead of rotating from "banking left" to "banking right", for example, it instantly snaps to the default rotation before beginning the smooth rotation. Here's what it looks like In addition, when I connect a joystick (instead of using arrow keys) to control the ship, I get a different problem The ship has literally no smoothing at all, rotating one to one with the direction the joystick is rotated in. Here's what that looks like Here's the code that controls ship movement public bool inverted true public float speed 20 speed modifier of horizontal vertical movement public float rotSpeed 120 speed modifer of rotation (ship tilting) public float ZRotMax 30f public float YRotMax 50f public float XRotMax 30f public float width 30 public float height 15 public float centerDriftStrength 5 lower is stronger, higher is weaker. Update is called once per frame void Update () Get input float controlHorizontal Input.GetAxis("Horizontal") float controlVertical (inverted ? Input.GetAxis("Vertical") Input.GetAxis("Vertical")) Add mild center drift float moveHorizontal controlHorizontal ((transform.position.x) (width centerDriftStrength)) float moveVertical controlVertical ((transform.position.y) (height centerDriftStrength)) Modify position transform.position (new Vector3(moveHorizontal, moveVertical, 0) speed Time.deltaTime) Cosmetic rotation based on controller input Quaternion oldRot Quaternion.identity Quaternion newRot Quaternion.Euler(XRotMax controlVertical, YRotMax controlHorizontal, ZRotMax controlHorizontal) transform.rotation Quaternion.Slerp(oldRot, newRot, Time.deltaTime rotSpeed) In particular transform.rotation Quaternion.Slerp(oldRot, newRot, Time.deltaTime rotSpeed) Seems to be what I need to look at. rotSpeed should cap the speed of rotation on the ship, so that it can't instantly rotate in a different direction. Right now, when rotSpeed is less than 120 or so, the ship twitches while rotating, and if it's particularly low, like 10, the ship barely rotates at all. (The rotSpeed variable doesn't seem to be working anyways setting it to 30000 or something doesn't make the rotation any faster.) Basically, I want the ship to always rotate smoothly, never jumping instantly from one rotation to the next. I'm not sure if I need to use Slerp for this, or if there's some better smoothing method available to Unity. Thanks, and if anybody knows of other ways to smooth rotation between constantly changing Vector3s Quaternions, please tell me!


Implementing DirectX 7 light attenuation in Unity's Universal Render Pipeline I am create a modern Unity based client of an old MMO from 2000, and I am working on implementing their lighting system. Based on the data I have reverse engineered, it looks like they used a custom attenuation formula. The original client uses DirectX 7. I have found a reference sheet for DX7 light. http developer.download.nvidia.com assets gamedev docs GDC2K D3D 7 Vert Lighting.pdf The relevant info starts at page 17. In the URP, in Lighting.hlsl, I have set up linear attenuation float range rsqrt(distanceAndSpotAttenuation.x) float dist distance( positionWS, lightPositionWS) half attenuation 1.0f dist range Looks good! https i.imgur.com 5bfJ5fF.png Everything looks good. Now I am trying to (based on the document) recreate the same linear attenuation. It should look something like this DX 7 float range rsqrt(distanceAndSpotAttenuation.x) float dist distance( positionWS, lightPositionWS) half c0 1.0f half c1 1.0f half c2 0.0f half d dist range half attenuation 1.0f ( c0 c1 d c2 d d ) This should give me linear attenuation according to the doc, but it ends up bleeding light way past the range of the light. So I am convinced the distance is wrong. What kind of value is expected here? Normalized distance? It doesn't specify. I have played around with the distance a lot. Set it to the attenuation in the first code example, to the raw value, and a bunch of other values. No luck https i.imgur.com JWJ0HF2.png Does anyone have any ideas?


Duplicating actor in Unity New to video game development and im working in unity on a Mac right now. I also have been using unreal on my pc figuring them both out. Im trying to (in unity) quickly copy prefabs by dragging them to different spots on mac? Basically the unreal engine equivalent to Alt dragging your actor on windows. I've tried looking it up and shortcuts dont help and randomly pressing buttons and dragging is getting me nowhere fast


How to use a sprite mask or shader to mask a text? I'd like to know what I need to learn to apply a shader to achieve masking on the text. Here is my text object in game, I'm using a sprite mask to mask the game objects on the card, they're all in their own sorting layer, the order number is 11. Here is my text in the inspector However, everything on the card is being masked except the text. If someone could tell me what I need to learn to solve this problem that'd be great, can this problem be solved using a shader?


Making animations not smooth while using Record button In my 2D sidescroller game, I want to separate the animations for the head and the body of my character. While idling, my charcter's body bounces slightly up and down (kind of a breathing motion). Thus, the head should keep up. However, when I press Record and make adjustments for the head, the head moves up and down smoothly instead of following the body frame by frame. How can I remove the smooth transitions from one position to the other? Here is a screenshot from Unity demonstrating the hierarchy and the animation keyframes.


Constraining camera bounds within bounds based on Unity UI object dimensions I have a perspective camera which has bounds which I wish to constrain within larger bounds. All the bounds are calculated in world space. The code for containing the camera within the constraining bounds is straightforward var camRect this.cameraComponent.GetCameraWorldRect() var correction Vector3.zero if (camRect.xMin lt constrainingRect.xMin) correction.x Mathf.Abs(constrainingRect.xMin camRect.xMin) if (camRect.xMax gt constrainingRect.xMax) correction.x Mathf.Abs(constrainingRect.xMax camRect.xMax) if (camRect.yMin lt constrainingRect.yMin) correction.y Mathf.Abs(constrainingRect.yMin camRect.yMin) if (camRect.yMax gt constrainingRect.yMax) correction.y Mathf.Abs(constrainingRect.yMax camRect.yMax) this.cameraComponent.transform.position correction This can be visualized as The problem I am facing is that I have a UI object that is covering the right hand side of the screen and I am uncertain how to correctly calculate the width of the UI object so that the constrained camera bounds can take it into account. The camera that is drawing the UI object is configured as follows The camera that is being constrained is configured as follows Apart from the layer, the parameters which affect the rendering of the objects for each camera configuration are the same. The UI object has the following configuration with a Canvas Renderer This is how I am currently attempting to calculate to width of the UI object but given that the UI is being rendered using a perspective camera I wasn't too certain that ScreenToWorldPosition was correct. private float CalculateMenuWidth() Generate padding to account for the side menu var canvas LevelEditor.Instance.Menu.GetComponentInParent lt Canvas gt () var menuRect LevelEditor.Instance.Menu.GetComponent lt RectTransform gt () var menuRectMax menuRect.rect.max canvas.scaleFactor var menuRectMin menuRect.rect.min canvas.scaleFactor if (this.cameraComponent.orthographic) return Mathf.Abs(this.cameraComponent.ScreenToWorldPoint(menuRectMax).x this.cameraComponent.ScreenToWorldPoint(menuRectMin).x) Perspective camera requires distance for ScreenToWorldPoint var distance Mathf.Abs(this.cameraComponent.transform.position.z) return Mathf.Abs(this.cameraComponent.ScreenToWorldPoint(new Vector3(menuRectMax.x, 0f, distance)).x this.cameraComponent.ScreenToWorldPoint(new Vector3(menuRectMin.x, 0f, distance)).x) However, the size of menu returned by the method above appears to be too large. How can I correctly calculate the width of the UI object so it appears that the camera constraints do not allow the camera to travel past the UI object? EDIT I've added a link to a Unity project which is the minimal working example for reproducing the issue. https www.dropbox.com s mq36mfqz5wvvsch CameraConstraintGUIIssue.zip The camera can be controlled with WASD to translate and the Shift key will speed up the movement. The camera is constrained inside the checkerboard. An offset is created so that the camera should stop moving to the right once the right edge of the checkerboard is adjacent to the left edge of the menu. Unfortunately, I can't seem to calculate the size of the menu correctly so this occurs. The code for constraining the camera and calculating the menu size is in EditorCamera.cs. Edit2 The constraint from KingDolphin The constraint I am attempting to calculate (quoted from above, An offset is created so that the camera should stop moving to the right once the right edge of the checkerboard is adjacent to the left edge of the menu.)


How can I override OnTriggerEnter? I am trying to extend Unity's BoxCollider class. So I am extending it in the editor like such using UnityEditor using UnityEngine CustomEditor(typeof(BoxCollider)) public class MyBoxCollider Editor public override void OnInspectorGUI() EditorGUILayout.LabelField("My Box Collider") base.OnInspectorGUI() However, I cannot figure out how to override OnTriggerEnter, OnCollisionEnter, etc. How can I override these? They appear to be declared as private in the base class. My end goal is that when I add a BoxCollider to a GameObject, it has a label in addition to its normal stuff. Then when BoxCollider's OnTriggerEnter method is called, it prints out what the label says before continuing on about its business. (This is a simplification, but I think it helps clarify my objective.)


Scaling material texture to be 1pixel 1 unit I have a mesh I use to render a sprite texture I set up in a material. This mesh is planar XY aligned and stationary. It's vertexes are generated from a PolygonCollider. The problem is that I'm using 1 PPU in the rest of my sprites, but the sprite rendered in the texture looks extremely small. How can I make the scale of the texture's material, so the size of a pixel in the material is equal to 1 unit? I can't just scale it, because I need it to be EXACTLY 1 unit.


Automated performance testing I'm wondering if there's anyway of automatically testing the performance of my game on multiple configurations because I know a game runs well on my computer but how do I know how well my game performs over a variety of hardware? Do I just simply have to rely on player feedback?


Physics.CheckSphere never returning true despite being called to where a hitbox is I'm trying to create a random level generator where I have a load of rooms 16x10 and I generate them when the player enters the room. I want to check the space where I want to place a room, in this case up for if there's already a room there. I've written this code to do that but it doesn't appear to be working. Currently it should ALWAYS return true (and not run the code) because the object it is on has a hitbox. I want it to hit triggers because then I don't need a physical block in the centre of every room (hard when the rooms are even both ways) Can you see what's wrong here? The code does spawn a block in the correct place. if (!Physics.CheckSphere(new Vector2(transform.position.x, transform.position.y), 1f, 6, QueryTriggerInteraction.Collide)) Get list of open bottoms getList("Assets Room Lists bottom.txt") Make a random number from the list int newRoomIndex random.Next(0, prefabObjects.Count) Get that object GameObject newRoom prefabObjects newRoomIndex Place it in the world in the correct position Instantiate(newRoom, new Vector3(transform.position.x 8, transform.position.y 15, transform.position.z), Quaternion.identity)


Difference between unity scripting backend IL2CPP and Mono2x IL2CPP is a Unity developed scripting back end which you can use as an alternative to Mono when building projects for some platforms. Note IL2CPP is only available when building for the following platforms Android AppleTV, iOS , Nintendo 3DS, Nintendo Switch, Playstation 4 Playstation Vita, WebGL ,Windows Store, Xbox One I have a project(unity 5.2) which has switched for Android deployment. I tried to switch my scripting backed from Mono2x to IL2CPP and its showing me that IL2CPP on Andriod is experimental and unsupported So, my simple question is that if it is still not supported then why the option has included, what is the fundamental difference between IL2CPP and Mono2x. Why I switched to IL2CPP scripting backend ? what are its pros and cons? I have also checked in unity 5.5.2 there is not IL2CPP option in windows platform deployment.


Unity 3D move kinematic rigidbody I'm trying to move a kinematic rigidbody (a spaceship) with this code float xSpeed 0.0f float ySpeed 0.0f float zSpeed 30.0f Vector3 moveDirection transform.right xSpeed transform.up ySpeed transform.forward zSpeed ShipRigidBody.MovePosition(ShipRigidBody.transform.position moveDirection Time.deltaTime) but moving the ship using ShipRigidBody.MovePosition makes it go through other objects with kinematic rigidbody. The collision detection of both objects is continuous dynamic and works for both other rigidbody objects and the object with the character controller. I've tried not using a kinematic rigidbody for the ship but when it gets hitted by projectiles (with rigidbody) it moves and starts spinning around. So my questions here would be Should I use a rigidbody for the NPC ship or use a character controller? There is any way to prevent a rigidbody from move after collision of other rigidbody, besides making it kinematic? How can I move a kinematic rigidbody so it doesen't go through other kinematic rigidbodies? Thanks for your help!


How to make UI Button to rotate an gameobject? I'm trying to make a button to make a gameobject rotate and stay rotating in its own axis (Y) but I cannot make it work... As far as I know it's very simple Create an empty gameobject (or whatever you want) Make a script and attach it to the gameobject Create public methods Link the gameobject with the script attached to the button onClick event Click the button and test the script My problem is that I don't know how I'm wrong here are the scripts of my project This first script is my attempt using keys, and it works like charm using System.Collections using System.Collections.Generic using UnityEngine public class TurntableRotation MonoBehaviour public GameObject turntable public float turnSpeed public bool canRotate false void Start () void Update () StartTurntableRotation() StopTurntableRotation() public void StartTurntableRotation() if (Input.GetKey(KeyCode.I)) canRotate true if (canRotate) turntable.transform.Rotate(Vector3.up turnSpeed Time.deltaTime) public void StopTurntableRotation() if (Input.GetKey(KeyCode.P)) canRotate false if (!canRotate) turntable.transform.Rotate(0,0,0) This second script is my work in progress using System.Collections using System.Collections.Generic using UnityEngine public class TurntableUIBtns MonoBehaviour public GameObject turntable public float turnSpeed This is my public method used by the button public void StartTurntableBtn() This is my attempt to write the code for the object to rotate turntable.transform.Rotate(Vector3.up turnSpeed Time.deltaTime) As far as my knowledge goes, it is supposed to work, but I have to click every time to rotate my object, my goal is to click the button and make the object rotate and stay rotating


Auto generate optimal direction for Unity Raycast with specifications How can I have a Physics.Raycast auto generate a direction for itself to try to hit a given target through a restricted window of space? Update After much work, my problem has slightly morphed into one about mesh colliders given a (convex) mesh collider, how can I detect all of the points intersecting with the collider? Or, if this can be done easily, can I get one Vector3 per object that is within the mesh collider? Update This is kind of a long question, so I'll try to explain it the best I can I have 3 GameObjects a source, a target, and a "window". This window sits between the source and target. I want the source to make a raycast that points in the direction of the target (not necessarily it's transform.position, just a direction that will make it hit the target) and this raycast must pass through (collide and continue through) the window GameObject I would like to automatically generate this direction for the raycast to follow such that 2 happens I would like this algorithm to also recognize if the above is not possible As an added item, I would like this raycast to pass through (collide and continue through) any objects that may be in it's way between it and the window Here's an image describing my issue in more detail How can I accomplish this? Thank you for your help in advanced!


ScriptableObject not working after build in Unity? I have a GameObject with a ScriptableObject on it, stats. It works fine in editor but when I try to build I get a message, A script behaviour (script unknown or not yet loaded) has a different serialization layout when loading. What is wrong here?


Idle Walk animation problem and double button input axes I have 2 problems with unity3d. First, I created an animator and attached it to player. In animator I put 2 condition, Speed and Running (first is float, second is boolean). Default Animation is Idle. Then player press W, I want animation to fade from idle to walk and when he stop press the button, I want the animation to fade from walk to idle. Here is my problem. When I press W, he make walk animation, but after it he play half of idle animation and after it he enter again in walk animation. How can I loop the walk animation until he release W? And if he release, even if the animation isn't totally played, I need the animator to make transition to idle. How can I make this "transition"? Then I release W, he just go from walk to idle animation without any transition (and it is a kind of wear). Second, How can I put 2 input buttons on axes? I mean If he press W, there should go vertical axes. When he press W Left Shift, there should go running axes. How can I attach 2 buttons to 1 axes? I am new in unity and I want to figure out how to work with this things.


Unity RectTransformUtility.ScreenPointToLocalPointInRectangle What does the unity's RectTransformUtility.ScreenPointToLocalPointInRectangle do I've read unity documentation but I didn't get the clear meaning.


UNET start game with friend by finding their name, Android There is a game at the google play store called Fun Run 2 Multiplayer Race. I loved its feature to find friends by writing their names, and then to play with them. Is it possible to achieve that with UNET? How? Another one is called Virtual Table Tennis. There I have a lobby full of people from whom I can choose. Can I achieve that with UNET? How?


2D diagonal movement using Rigidbody2D I have a problem with 2d player movement, as I am unable to move on the Y axis. Yet, the movement on the X axis is working as intended. Below, you can see my code public Sprite directionUp public Sprite directionDown public Sprite directionLeft public Sprite directionRight public float speed 0.1f public byte direction 0 0 up, 1 right, 2 down, 3 left private SpriteRenderer spriteRenderer private Rigidbody2D rb2D private Sprite directionArray Use this for initialization void Start () rb2D GetComponent lt Rigidbody2D gt () spriteRenderer GetComponent lt SpriteRenderer gt () directionArray new Sprite directionUp, directionDown, directionLeft, directionRight if(directionArray 0 ! null) spriteRenderer.sprite directionArray 0 Update is called once per frame void Update () if (Input.GetKeyDown(KeyCode.Keypad7)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.Keypad9)) rb2D.MovePosition(rb2D.position new Vector2(1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 else if (Input.GetKeyDown(KeyCode.Keypad1)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.Keypad3)) rb2D.MovePosition(rb2D.position new Vector2(1f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 else if (Input.GetKeyDown(KeyCode.W) Input.GetKeyDown(KeyCode.Keypad8)) rb2D.MovePosition(rb2D.position new Vector2(0f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 0 else if (Input.GetKeyDown(KeyCode.S) Input.GetKeyDown(KeyCode.Keypad2)) rb2D.MovePosition(rb2D.position new Vector2(0f, 1f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 1 else if (Input.GetKeyDown(KeyCode.A) Input.GetKeyDown(KeyCode.Keypad4)) rb2D.MovePosition(rb2D.position new Vector2( 1f, 0f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 2 else if (Input.GetKeyDown(KeyCode.D) Input.GetKeyDown(KeyCode.Keypad6)) rb2D.MovePosition(rb2D.position new Vector2(1f, 0f)) if (directionArray 0 ! null) spriteRenderer.sprite directionArray 3 By the way, please keep in mind I am quite new to Unity. EDIT 1 I have attached the entire script, some of the variables are unused right now(was testing other methods of movement). I tried to both Keypad 1, 3, 6, 9, as well as the combinations which I didn't get to work yet (but this is off topic and I will look into it once I will get the Y axis to move). Thanks, Zryw


Unity How does Time.smoothDeltaTime work I can't seem to find any actual information on what Time.smoothDeltaTime does or how it works. I would assume it takes a rolling average of previous deltaTimes but how does it do that? Is the average asymptotic? How sensitive is it to outliers? What is it's actual intended use case? If anyone could explain how it works, or link to a resource on what it is doing it would be really helpful.


Unity error after adding skybox material So I added the night material from the fantasy skybox asset I download from the asset store and the rest of my objects turned white for some reason I figured it was just a glitch like the light baking and it would be okay when I deployed my project Well I saved and built my project as usual and the objects all turn pink as if their materials did not exist and every time I go to play the game I receive the following error 'Assets Build ParcoreBeast Data Managed Assembly CSharp.dll' shouldn't be queried by IsAssemblyCompatible, missing IsInternalOrCompiledAssembly check ? UnityEditorInternal.InternalEditorUtility GetMonoIslands() UnityEditor.SyncVS SyncVisualStudioProjectIfItAlreadyExists() How do I fix this?


Coroutine not working (Unity) I made this code because I needed an image to display a couple seconds after an enemy spawns, but for some reason I can't make it work. There's no error in the console, but it doesn't display the image and I don't know what to do. Here's my script (it's attached to the enemy prefab) public class enemyAttack MonoBehaviour public float time 5f private IEnumerator coroutine public Image image private float t 5f void Start () image.gameObject.SetActive (false) image.enabled false coroutine nombredeCorutina (time, image) StartCoroutine (coroutine) private IEnumerator nombredeCorutina (float t, Image im) image.enabled true im.gameObject.SetActive (true) yield return new WaitForSeconds (t) coroutine nombredeCorutina (time, im) StartCoroutine (coroutine)


Calculate the starting position of a turning aircraft with inertial force to make it stop at desired position and heading Continued from the answer here, I have some problem when the aircraft in my game has inertial forces after going forward and turning itself. To illustrate, from the following image (https imgur.com a Xvqu2A7) the aircraft is moving from the point A gt B gt C' gt D. I planned to maneuver the aircraft from the point C' which is the point that would make the aircraft stop at the point D after turning with its full performance (using minimum turning radius). The question is how do I calculate the position of the point C' to make the aircraft roughly stop at the point D with the desired position and heading (It is roughly since there is also an inertial force after stopping the aircraft's engine.)? Any suggestions and answers would be appreciated.


Surface shader with VertexLit causes black object I wrote the simplest possible surface shader Shader "SimpleSurf" Properties MainTex ("Base (RGB)", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM pragma surface surf Lambert sampler2D MainTex struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) half4 c tex2D ( MainTex, IN.uv MainTex) o.Albedo c.rgb o.Alpha c.a ENDCG FallBack "Diffuse" When the "Forward" rendering path is enabled the object looks fine! But when the "Vertex lit" rendering path is enabled, it looks became black Why it happened? How can I use surface shaders (or maybe write a Vertex Fragment shader which will consider spot lights) which do some effects in VertexLit path?


How to hide a sprite on trigger when the player enters the trigger zone? I am making a roof for my 2D top down survival game, and I want to make it so that the roof disappears when the player enters the building, and re appears when they leave. Here is the code I've written so far using System.Collections using System.Collections.Generic using UnityEngine public class Roof MonoBehaviour public GameObject roofGameObject void OnTriggerEnter2D(Collider2D collision) roofGameObject.SetActive(false) void OnTriggerExit2D(Collider2D collision) roofGameObject.SetActive(true) I got it to work so that, when I go in, the roof it disappears. But when I leave it stays disappeared. How can I fix that?


Apply transform.Translate to a specified object in the script In Unity3D, if I place a C script including transform.Translate on an object "A" in the hierarchy, it animates the translation of this object A. How in C can I apply that transform.Translate effect onto another object defined in the script itself? I want to write a script similar to this using UnityEngine using System.Collections public class Create Objects MonoBehaviour public float moveSpeed 2f public Transform otherObject void Update () if (Input.GetKeyDown (KeyCode.Q)) GameObject Object1 new GameObject ("Object1") otherObject.Translate (Time.deltaTime moveSpeed, 0, Time.deltaTime moveSpeed) But somehow I want that otherObject that I'm translating to refer to the Object1 I created when the user pressed "Q". Thanks DMGregory for your last code!... and finally, same as before but the objects are created and translated from position of each previous object creates. What is the new C code?


Can I replace the source image of slices by script? I have a Unity2D prefab that uses several slices from a single PNG. (in it sprite renderer, and in its animation clips). If I replace that PNG in the Finder, all slices taken from that PNG are automatically updated, which is great. But I want to do this by script just replace the PNG where all slices are taken from, with another PNG. This is so that each of my prefabs instances can all use a different spritesheet PNG source for its slices. Is this possible in Unity?


Add Atten property in Unity Shaderlab In Unity Shaderlab shader, Is there any way to apply Atten value? Using surface shader, and vertex fragment shader I can do it easily. But, I didn't find any reference to do that in Shaderlab syntax. Shader "Diffuse" Properties Atten ("Light Attenuation Power", Float) 1.0 lt how to apply? Color ("Main Color", Color) (1,1,1,1) MainTex ("Base (RGB) Transparency (A)", 2D) "" SubShader Pass SetTexture MainTex constantColor Color combine texture constant, texture constant this makes syntax error. constantColor Atten Color


How to resolve push block physics in a 2D side scroller puzzle I've been working on a 2D tile based side scroller puzzle game in Unity with obstacles such as doors, keys, fans, portals, etc., but one type of obstacle, push blocks, is giving me some issues. Here is how it is supposed to work The player (an certain other obstacles) can push the block from either side, and it should move smoothly until it is either blocked by another obstacle or there is no ground beneath it If it is pushed off an edge, it should fall into whatever hole is there, even if it is a snug fit. (left picture) The top of the block should be flush with other blocks or surfaces when they are at the same level of height. There are no slopes in the tileset, so this would happen often. Motion across the combined surfaces should be smooth, with no way to wiggle between adjacent blocks. (right picture) It must be able to respond to other forces in the game such as fans and gravity switches. I have been using Unity's built in physics engine, which has worked great for all other components of the game, but sometimes allows blocks to jump over holes, and sometimes blocks get stuck between other blocks when they shouldn't, so I have tried abandoning Unity's physics and made my own. It just made the rest of the game more glitchy and still failed to resolve the block problems. If I change just the way the blocks physics work, I may be able to lock its position to a grid, where it cannot be left between tiles. That way I could get the more snug collisions to work. If I did this though, it would cause problems with the rest of the interactions. A floating block with a fan underneath it bounces around too much to be locked to a grid. Does anyone know a design that would allow all these requirements of be met?


nullObjectException in OnDrawGizmos Function I was studding A Algorithm and it is showing a nullObjectException in my OnDrawGizmos function whenever it finishes compiling the code. Here is my code can anybody tell me what I am doing wrong? using System.Collections using System.Collections.Generic using UnityEngine namespace PathFinding public class Grid MonoBehaviour public Transform Startpostion public LayerMask Layer Mask public Vector2 gridWorldSize public float nodeRadius public float Distance public Node , grid float NodeDiameter int GridSizeX, GridSizeY public List lt Node gt FinalPath private void Start () NodeDiameter nodeRadius 2 GridSizeX Mathf.RoundToInt (gridWorldSize.x 2) GridSizeX Mathf.RoundToInt (gridWorldSize.y 2) GridCreator () void GridCreator () grid new Node GridSizeX, GridSizeY Vector3 bottomLeft transform.position Vector3.right gridWorldSize.x 2 Vector3.forward gridWorldSize.y 2 for (int y 0 y lt GridSizeY y ) for (int i 0 i lt GridSizeX i ) Vector3 WorldPositionOfCurrentNode bottomLeft Vector3.right (i NodeDiameter nodeRadius) Vector3.forward (y NodeDiameter nodeRadius) bool Wall true if (Physics.CheckSphere (WorldPositionOfCurrentNode, nodeRadius, Layer Mask)) Wall false grid i, y new Node (Wall, WorldPositionOfCurrentNode, i, y) private void OnDrawGizmos () Gizmos.DrawWireCube (transform.position, new Vector3 (gridWorldSize.x, 1, gridWorldSize.y)) foreach (Node n in grid) if (n.is Wall) Gizmos.color Color.white else Gizmos.color Color.yellow if (FinalPath ! null) if (FinalPath.Contains (n)) Gizmos.color Color.red Gizmos.DrawCube (n.postion, Vector3.one (NodeDiameter Distance))


How to connect a 3D head to a body? I am new to Unity, game making, etc. I have downloaded the trial version of Avatar Maker and a similar Unity plugin called Didimo Editor, with the hope of using their features to make game characters that look like real people, using photographs. They both do more or less what I want. However, both tools output only heads, and do not connect them to 3D bodies. Avatar Maker has another plugin that allows for this, but it is only for male bodies and most of its features are not to my liking. So my question is how can I put these heads on working 3D bodies? The trailer for Didimo Editor seems to confirm that it can, at least, and Avatar Maker is able to export its heads to OBJ, FBX and Prefab, so I'm assuming maybe there is a way to do that too.


Problem with Raycasting in a 2D Game I'm new to using unity and came across a problem when I was following a tutorial. The game is in two dimensional space, and when my player walks over a certain tile the detection never goes off. Here's the code that I have, function calculateWalk() yield WaitForSeconds(0.3) var hit RaycastHit if(Physics.Raycast (transform.position, Vector3.down, 100.0)) Never evaluates to being true var distanceToGround hit.distance Debug.Log("Hit") if(hit.collider.gameObject.tag "tallGrass") walkCounter Debug.Log("Tall Grass") END if END if END calculateWalk() I've made sure to attach the script to my player, as well as tag the tiles that I want with "tallGrass". I've followed what was done in the tutorial, but for some reason it's not working out for me, not sure if this is all the code needed to help solve this problem, if more information is needed let me know, I also set my player 1 unit above the tiles.


2d games unity vs Flash do people find unity better than flash for 2d games while unity is 3d engine , or Flash still better because it's made for 2d games and flash can get the job done faster ,and now flash is better for ios android 2d games . so what platform is the best for 2d games?


Collider Effeciency Question I'm creating a game where hundreds of rockets with colliders attached are shooting at a player. Should I write my script where 1 The player script reads the collision from hundreds of rocket colliders or 2 Each rocket collider updates information when colliding with the player Thanks!


Make a light only affect one object I'm wondering if it's possible to make a light source only affect one object? I know that it's possible to use layers and culling mask, but then I would need one layer for every single object which is not possible. Is there a way for example that I could make only children or siblings be affected by a light source? Or other solution? Have a nice day! Update 1


How to load values into a script from a file? I have a prefab of a "generic unit " each one has a script with some public variables name, health, and attack. Currently, I am manually making copies of that prefab and editing their names, health and damage values in the inspector. This seems unwise to me. I would rather be able to make a simple file for each unit type, containing its important information, like this name "Archer" health 3 attack 1 And so on. Then, I would like to be able to turn that into actual GameObjects in Unity, presumably by instantiating the prefab and filling in its values with values from the file. I could then make a script that runs when the game begins and iterates through, making all the objects I need. However, I do not know the proper way to go about doing this. Is there some way to read files and slot values into variables of a script? To be clear, I would like to be able to tell Unity to make an Archer, then have it read the Archer file, look up its values for health and attack, then instantiate a copy of the Generic Unit prefab and slot the values that it read into the public variables of a script component of the newly created game object.


How to throw a ball vive controller object in unity3d I have this simple line of code that through the ball. Under arm throw is right while if i try through any else ways its through movement is weird like a curve from down to up. what i am doing wrong. how do i through the ball using controller (touchingObject) object direction correctly realistically. Additionally i am also encounter a problem that if i through one ball all the previous throw balls move in that direction also. what the heck is that? gameObject.GetComponent lt Rigidbody gt ().AddForce(touchingObject.transform.forward 1000)


How can I adapt A pathfinding to work with platformers? I have an A implementation that works in "top down" situations where gravity is not taken into account for pathfinding. But, I am looking to modify to work in a 2d platformer situation. I am using the Unity Engine in C but any examples or even pseudocode would be really helpful. I have found a source so far but it haven't been that helpful as I am not understanding the way they have adapted A , I have listed them below. http gamedevelopment.tutsplus.com tutorials how to adapt a pathfinding to a 2d grid based platformer theory cms 24662 (Very specific to authors implementation and hard to understand)


How to make child object a member of two parents in unity? So I have an parent game object that has multiple objects. This format is desirable GameObject object1 (abstract) subobject1 object2 (abstract) subobject2 object3 (abstract) subobject1 subobject2 There are two objects in the scene, subobject1 and subobject2 The problem is when i drag and drop one subobject from an object it removes it from the other object. When i copy the subobjects to another object, there are now two. I hope this makes sense.


What causes this graphics quality difference between WebGL Build and Unity 5 Editor? The Editor version and WebGL version of my Minesweeper clone have some graphics quality differences. I chose 'Fast' option when building this deployment. Is this the difference between 'Fast' and 'Fastest' options of Optimization Level in Build Settings, meaning that if I choose the 'Fastest' option, the WebGL deployment will be the same as Editor version, unlike below? If not, why this happens?


Override the position of bodypart with script on top of animation I have a character with an Idle and Move animation. Now I want to create an Attack animation. Here I want the hand to move towards the mouse position and back, using a script. The other hand should still follow the Idle or Move animation. When I use a script in FixedUpdate() to do this the position of the hand still follows the animation. If I use LateUpdate() and set hand.transform.position, this seems to represent the local position and not global position. Is there a proper way to create this Attack animation? using UnityEngine public class Attack MonoBehaviour public Camera camera public Transform body public Transform hand public string button public float time 5f public float begin 3f public float end 6f float step 0f bool pressed false float currentTime 0f int direction 1 private void Start() step (end begin) time private void Update() if (!pressed amp amp Input.GetButtonDown(button)) pressed true private void LateUpdate() if (pressed) setCurrentTime() Vector2 mouse camera.ScreenToWorldPoint(Input.mousePosition) Vector2 direction (mouse (Vector2)body.position).normalized hand.position (Vector2)body.position direction (begin (step currentTime)) void setCurrentTime() currentTime currentTime direction Time.deltaTime At End if (currentTime gt time 2) float overhead currentTime (time 2) currentTime currentTime overhead direction 1 Back at Begin if (currentTime lt 0f) pressed false currentTime 0f direction 1


How to make a rigidbody come to rest faster I'm trying to move around a 3D rigidbody in Unity 2018.1.0f2 Personal. I am using a C script with the basic vector3 and velocity stuff from a YouTube video using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour SerializeField private Rigidbody playerBody private Vector3 inputVector private float xMovement private float zMovement SerializeField private float playerSpeed private float maxSpeed Use this for initialization void Start () playerBody GetComponent lt Rigidbody gt () playerSpeed 1 Update is called once per frame void Update () xMovement Input.GetAxisRaw("Horizontal") playerSpeed zMovement Input.GetAxisRaw("Vertical") playerSpeed inputVector new Vector3(xMovement, playerBody.velocity.y, zMovement) playerBody.velocity inputVector It works great with a cube I put it on, except for this if I move the rigidbody and then stop, it takes a long time for it rotate from go only one of the edges or corners just touching the ground (screenshot of what I mean, another screenshot) to resting flat. How can I make it fall back to stability faster?


Texturing different block types on an optimized voxel mesh I have a cubic world (like Minecraft) where I'm generating chunks. In those chunks, only visible vertices and faces are generated. Currently, it means that if I have a 2x2x1 chunk, it will generate 8 triangles for the top part (2 for each block). I'm trying to generate only two following this greedy meshing method If I combine adjacent faces together, I'd still like to be able to draw transitions in materials between adjacent blocks, something like this As you can see it has 3 different tiles grass, dirt grass transition, and dirt. Currently, my shader looks like this Shader quot MultiTexture Diffuse Worldspace quot Properties Color ( quot Main Color quot , Color) (1,1,1,1) TexAbove ( quot Above texture quot , 2D) quot surface quot TexSide ( quot Side texture quot , 2D) quot surface quot TexBelow ( quot Below texture quot , 2D) quot surface quot TexTopSide ( quot Top side texture quot , 2D) quot surface quot Scale ( quot Texture Scale quot , Float) 1.0 SubShader Tags quot RenderType quot quot Opaque quot CGPROGRAM pragma surface surf Lambert struct Input float3 worldNormal float3 worldPos sampler2D TexAbove sampler2D TexSide sampler2D TexBelow sampler2D TexTopSide float4 Color float Scale void surf (Input IN, inout SurfaceOutput o) float2 UV fixed4 c if(abs(IN.worldNormal.y gt 0.5)) UV IN.worldPos.xz c tex2D( TexAbove, UV Scale) else if(abs(IN.worldNormal.x) gt 0.5) UV IN.worldPos.yz c tex2D( TexSide, UV Scale) else if(abs(IN.worldNormal.z) gt 0.5) UV IN.worldPos.xy c tex2D( TexSide, UV Scale) else UV IN.worldPos.xz c tex2D( TexBelow, UV Scale) o.Albedo c.rgb Color ENDCG How would I modify this shader to work with faces that have been merged together? Or would I have to keep separate faces per block and handle them individually?


Low fps on Arm Mali GPU I was trying to google and understand my problem in two weeks but i am defeated, so i am asking for help. The main problem is that my custom unlit frag shader after certain amount of time on devices with mali gpu starts to drop fps i see it via fps counter in the cpu section. I dont know why in that section and not in render section, but with out this fps counter i can still feel the drop of fps. So on Samsung S4, Samsung sm t 380, xiaomi redmi note 5, samsung tab s2 is all ok, the drop was only on samsung s6 to solve the problem i just half the resolution by Screen.SetResolution function. I was thinking that drawing the full screen sprite on such a high res device is the point. Then i can test app on samsung sm t580 and the drop was there this device has low resolution than S6. I assume that the problem in arm mali gpu or i am sure in my hands. So again, i am rendering full screen with draw mode tile(countinuous) sprite with 3 textures, just changing theirs uvs in vert func and apply in fragment. This makes distorting effect. The shader show that i have 10 maths and 4 textures, yes 3 textures but i am making 4 sampling. The textures are 256x256 with repeat mode. I was trying diferrent textures compressions, dxt5, etc1 2, alpha8, R5 no effect. I was trying to different precisions half and float in different parts in shader no effect. I was thinking in alpha, so i took textures without alpha and not getting it from tex2D. Even the size of textures is doesnt matter, even if they 64x64. The dance with ZTest, ZWrite, Blend, Queue RenderType, other params no effect. My guess was that maybe on mali uv TEXCOORD0 must be only float2, not float3 or float4 no effect. I am applying Time.y and replace it with float from script no effect. Only reducing amount of tex2d in shader is working. Why? What i m doing wrong?


"SetSelectedGameobject" only highlights button on second try (Unity 2017.3) To support the use of a gamepad in the options menu I set SetSelectedGameObject and firstSelectedGameObject (which doesn't seem to do anything) to the button in the upper left, so it's highlighted. This works fine in my pause and option menus (panels that are enabled disabled) but there's also a third panel that displays the controls as an image. On this screen the first button is set as selected but it doesn't get highlighted until I go back to the pause menu and then open the "controls" screen again. The Hierarchy The ControlsPanel looks like this click All 4 buttons are set to "automatic" and they're all accessible to the gamepad but, like I said, the first one ("Keyboard") doesn't light up the very first time I access the panel. It should be like this Click on "Controls" in the pause menu ControlsPanel is enabled "Keyboard" button is highlighted Pressing right on the gamepad highlights the next button ("Controller") What actually happens Click on "Controls" in the pause menu ControlsPanel is enabled "Keyboard" button is still grey Pressing right on the gamepad highlights the next button ("Controller") Press the "Back" button ("ControlsPanel" is disabled and "PausePanel" enabled) Click on "Controls" again This time the "Keyboard" button is highlighted The "ControlsPanel" script public Image pic public GameObject controllerChoicePanel public GameObject firstControls private String controls private bool windows void Start() controls GetControls() windows GetOS() pic.sprite Resources.Load lt Sprite gt (controls) if(windows) controllerChoicePanel.SetActive(true) EventSystem es EventSystem.current es.firstSelectedGameObject firstControls es.SetSelectedGameObject(firstControls) Any idea why it would work fine in my pause options menu but not in the "Controls" one, even though I'm doing the same thing?


2.5D UI, perspecitve view, distort objects by angle but not position Instead of thousand words, a few pictures to explain what I want to achieve How do I get the merit of UI objects rotation in perspective projection, but ignore the position of an object(as in Overlay Canvas)? UPDATE 1 Can you include an example of what your full UI or scene would look like? A usual bar which is used to hold stuff like score. Same base prefab is used for mana health and any other UI parameter on screen. But bars have different rotations, so here is one solution have a unique sprite for every special rotation and have a bunch of prefabs(nah). Or have one sprite, one prefab and set the rotation in scene(that's the way). Is there a reason you are asking for this in perspective projection? Just because I want to be able to rotate UI objects in scene and show the "depth" of rotated object. I'm not particularly stuck onto perspective projection, as long as I can achieve the "want" look without actually redrawing sprites for every unique angle. so I'm not sure what you are asking for. Are you asking how to skew an image in 2D, so that it looks like a 3D perspective projection? I know it sounds crazy, since it's obvious that in perspective looking at object which is above camera you get that "looking from down" look. And yet I feel you are onto something(and now am I), one way of thinking is actually to skew a 2D image to simulate rotation as in perspective view!


How to run different animations with same suffix for different public objects? I would like to be able to run the corresponding animation (ending with "Get" in the title) for whatever item GameObject I plug into this treasurebox. I made 2 prefabs for "item get" animations today. Both GameObjects consist of 3 sprites The image representing the item, and 2 lightray images that I enable disable in alternation to get a halo effect (see animation below). You can see the 2 prefabs and their corresponding animation components in the Project panel These next two images show how similar the animations are they even both require two of the same sprites, flareA and flareB. Here is the code I am currently using to set the state of the ItemBox GameObject and run the animations. You can see that while the itemGet prefab is public (that is, I can plug in whatever gameobject I want in the editor), line 27 explicitly calls for the animation belonging only to the turd item. using System.Collections using System.Collections.Generic using UnityEngine public class ItemBox MonoBehaviour bool disabled false private Animator anim public GameObject itemGet null void Start() anim GetComponent lt Animator gt () if (!disabled) anim.Play("ItemBoxIdleState") void OnTriggerEnter (Collider other) if (!disabled amp amp other.gameObject.tag "Player") anim.Play("ItemBoxGetItemState") GameObject itemClone Instantiate(itemGet, transform.position new Vector3(0, 0.375f, 0), Camera.main.transform.rotation) itemClone.GetComponent lt Animator gt ().Play("turdGet") Destroy(itemClone, 1.6f) disabled true How can I change line 27 (the line before 'Destroy') so that it runs the appropriate " Get" animation for whatever itemGet object I plug into the inspector? I think I am already close. I intend to make more items (not too many for now) and the animation I want to play will always be structured like "Get". UPDATE 07 29 19 I tried making a public AnimationClip object in the ItemBox script and putting that name in quotes for line 27 and thw script still works, but now I get an index error saying the animation state was not found. I don't think I can plug the name of the public variable into the .Play("") quotes and make it work I think it only worked because there is only one animation for that item anyway. I ended up removing this new variable and just keeping the .Play("") part as empty quotes and it still works. I might decide to add more animations to these item objects later so I still need to know how to specifically play the animation that ends in "Get".


Lighting large scene with dynamic lights Unity3D I am working on a game project where most of the action takes place in a large scene that is built to look like a space station. Because it is all technological and enclosed, I can't use a directional light to light the whole scene, and I need to be able to change the color of the lights for an alarm system. I can't bake the lights, because then I can't change their color, and I can't leave them all as dynamic lights, because I have about fifty spot lights, and they take up a huge amount of memory, so much so that the lights can't even render on mobile devices. Is there any way to do this without baking? I am getting about 3000 batches in the Unity Editor Stats on average, in some places it is higher. Even viewing the game in full screen in the editor makes the game run super slow because of the amount of rendering it has to do, and I have a pretty new computer. Here's a picture of my scene (As you can see, it is fairly large as you are able to see the UI box clearly from the scene editor) And here's the Stats box Here is an example of my scene in play mode UPDATE I removed the shadow casting, which isn't necessary for my project, and it improved the framerate slightly, and the batches number is smaller, averaging out at about 1500 now, but the performance still is not optimal.


Count Unity terrain size In blender? My unity terrain size is 150 150, and I want to create a plane in blender have the same size. How to figure the correct size ?


Scene dark when perspective camera is far from scenery I can't find anything about this subject in the docs or forums to know if this is normal behavior There seems to be a direct correlation between how close to the scenery my camera gets and how brightly lit the scene is. My camera is able to move up to 200 units from Vector3.zero. Here are two shots of the same piece of scenery one close up, one far away The camera is set to perspective, using deferred rendering. Things I've tried Turning off post processing Using auto expose in post processing Changing to orthographic (removes the issue, scene is uniformly bright at any distance) Changing the FOV Changing global lighting to use color rather than skybox Putting some lights at altitude This may be normal behavior amp I just havent noticed before. Can anyone confirm? Is there some way to prevent this happening? I don't want to use an orthographic camera but I do want the scene to be evenly bright at any distance from the camera.


Setting up a low res viewport to stretch in Unity I am working on porting a low res game over to Unity. In my previous engine, I had the option to set a native resolution (say, 160 x 144), and it would automatically stretch when the player entered fullscreen (with options for whether you wanted to keep the same aspect ratio, or stretch). I am having trouble figuring out how to set up something similar in Unity. I see that you can play around with resolution settings from Edit Project Settings Player. I tried various combinations of Default Is Fullscreen, Default Is Native Resolution, and Default Screen Width and Default Screen Height, but I haven't been able to get it to work. When I play the scene in the editor, the viewport is still much larger than my desired resolution. And when I Maximize On Play, the FOV is even larger. I Googled around, but couldn't find an answer that helped. Any advice?


Can Unity censor my content or invalidate my license for offensive content? If I make an offensive game can they pull my license and prevent me from selling my game? Like we're talking think of the most offensive thing you can think of you're in charge of the most efficient genocide against some specific racial religious political group, your choice... now imagine the game is mocking victims and generally being extremely rude, violent, and insensitive. Now I have no intention of making such a horrible game but I am using an extreme example to ask my question. It's not unheard of for less extreme things to get blocked by brands who didn't want to associate with them, for example I saw that Apple removed the Confederate flags from Civil War games in the App Store. Would Unity be able to prevent me from using their game engine or selling my game after I had already purchased appropriate Unity licenses and completed the game? Do they have that kind of power with their licensing model? Or would even the most extreme cases still be legally allowed to sell the content? I want to make something that may have some mildly provocative divisive content (not as offensive as say, South Park, which I know was made in Unity, but more serious than South Park) and I'm just making sure I don't get a bunch of work done and then get disappointed later, wishing I had gone with some kind of more free open engine.


How are methods like Awake, Start, and Update called in Unity? I'm developing with Unity 5 and I know that there are some methods you can use like in the code below public class MyGameElement MonoBehaviour private void Awake() private void Start() private void Update() private void FixedUpdate() and more I know what they do but I find it strange that the methods can be private. However they are not called into my code I've written. Here you've an image with code lens (I use VS 2015 Professional for coding) where you can really see that it has zero references. The second 'strange' thing for me is that the methods aren't overwritten. So my question is now is there anything that Unity has implemented into the MonoBehaviour class that the methods can call?


Per component Shader Blend in Unity Context I'm writing a 2D mobile game in Unity where the graphics are essentially black lines drawn on a background image plus some lighting. Running full RGB calculations for every step seems like a waste of processing power. What I'd like to do is render everything in grey, alpha and then multiply by the sRGB background image in a separate shader at the end. Actually, ideally, I'd like basically to specify custom components like grey, highlight, additive, alpha , each of which can be ignored in a given pass, and then do a custom operation with those when I apply the background image, like ceil(src (dst.r dst.g)) half4(dst.b). I can figure out how to do that between 2 textures within a shader, but not between texture and screen (a.k.a. src amp dst). Question Basically, is there a way of writing a per component replacement of the built in Blend functions? Because something like Blend SrcAlpha OneMinusSrcAlpha only works with the full float4 or half4 vectors. Or do I need to grab the screen like a texture and handle it within a pass block, and then do Blend Off or Blend One Zero? Or do something with RenderTextures perhaps? My intuition suggests that that would undo some of the efficiency I'd gained in previous steps, though...?


How to disable collider2D when another gameobject is on top of it Each black colored square has a BoxCollider2D. How can I disable the collider after I put another game object on top of it? Here is the sample output


Optimization of Cube based World I'm currently working on taking an idea I've been toying with in C and bringing it into Unity, but I'm struggling to figure out how to make it performant and how to do things the "Unity way". My world is made up of cubes and cube shaped tiles viewed from a fixed angle ( la Monument Valley). I've watched their behind the scenes video and seen that they have a step in their workflow that removes the unused faces from their cubes and combines them into quads. I want to achieve something similar. Ideally I want to build up my world using a bunch of prefab cube objects (with different textures and components) and then run some kind of process over my scenes before I export play to optimize them (otherwise I'm going to be doing potentially thousands of draw calls that I don't need to do and have lots of colliders I don't need). My questions are as follows What hooks does Unity provide to do this sort of processing? Should I be using PostProcessSceneAttribute for this? I understand that I can use Mesh.CombineMeshes to combine my cubes, but what about for their colliders? How can I determine groups of cubes that are touching (for removing faces and combining colliders)? In my C project I keep all of the blocks in a 3D array and use that, but using the Unity editor to place the blocks means I don't have this available. Is there a way I could easily build one from my scene, or is there a more "Unity" way of doing this? Is my approach sensible? Or should I drop the idea of placing individual cubes in the editor and take a different approach?


Rotate perspective camera to align screen width to procedural object's width (Unity, C ) I give up. After much trying and searching, I have to say I was unable to achieve the following task, for which I must call for your wise advice. In my current Unity 5 application (using C ), there is a procedurally generated object (therefore with variable shape) to which the camera should be aligned when players hit a given key. By aligned, please understand it making the width of the screen parallel to the longest part of the object. The idea is represented in the following picture, where in black one can see the irregular object, in yellow is the bounding box. In other words, it means that I want the camera to be rotated so to align to the longest side of the object's bounding box. I tried that. Still, I was unable to properly calculate the correct angles so to rotate the camera in a way that the horizontal axis of the screen becomes parallel to the width of the objects' bounding box. Any help would be much appreciated.


What does 'vertex splitting' mean? In the documentation of MeshUtility.SetPerTriangleUV2 it is said the following Will insert per triangle uv2 in mesh and handle vertex splitting etc. What do they mean by 'vertex splitting' ?


How to handle data for a competitive multiplayer games I am kinda new to Multiplayer Games and I am really wondering how I should handle my data Should each player send and update their data to the database (server) everytime one of their essential variables changes (like health or ingame currencies), or should they save the data as long as the game is running and then update the data all at once at the end of, lets say, each round? I was thinking about using Firebase and Unity and here's a scenario Let's say 2 players connect to a game. Then one of them gets damage and the other one gets gold. Does the data change get sent to the FireBase Database immediatly or should I just update everything when the round ends they disconnect?


How to prevent "reverse" displacement from a collision? In my game I can throw a hammer. The hammer moves based on physics in Unity. The hammer destroys the first object it touches. I want it to continue moving as though it didn't touch anything when this happens. To try and achieve this, I made it destroy objects using a separate, larger trigger collider, intending to destroy the object before the physical collision occurs. However, when moving at very high speeds (as in the GIF), both colliders hit at once, so the hammer moves and the object deletes. How can I prevent the hammer from moving when before the trigger occurs, or (I suppose more realistically) "reverse" the movement such that there's no perceptible collision? I tried using the impulses from each of the contacts in the collision to apply forces in reverse, but didn't really understand what I was doing and ultimately failed. NOTE I cannot simply disable the physics collider, because it doesn't destroy everything.


Unity3D Smooth rotation for seek steering behavior I am trying to implement Reynolds' seek steering behaviour, but I am having problems on the rotation part. This is what I have void FixedUpdate() get position of current waypoint Vector3 targetPos new Vector3(path currentWaypoint .x, transform.position.y, path currentWaypoint .z) velocity vector towards target Vector3 desiredVelocity targetPos transform.position calculate the steerforce required for the desired velocity based on current velocity Vector3 steerForce desiredVelocity currentVelocity steerForce new Vector3(steerForce.x, 0, steerForce.z) steerForce Vector3.ClampMagnitude(steerForce, maxSteer) create a move vector to be added to agent's current position Then normalize it so it can be scaled according to the agent's max speed Vector3 moveVector steerForce.normalized moveSpeed Time.fixedDeltaTime transform.Translate(moveVector) How would I do it so my agent will be rotated smoothly based only on the code above? I tried rotating based on the current velocity, but the agents is rapidly rotated in one frame towards the target waypoint. I am not working with rigidbodies. Am I doing something wrong? What am I missing? Thanks, Jack


Is it possible to export animations from Blender to Unity prefab without re exporting entire character? I have a fully rigged and animated character that I recently exported from Blender as an FBX to Unity. I need to make more animations for the character now but I am very tired of exporting the entire character every time I make a change. I do not need to update texture coordinates or vertex weights (probably). Is there a way to record a new animation in Blender and attach it to the existing Unity character? Or alternatively, is there now a viable way to produce quality animations for characters inside of Unity? My character needs to move fingers and toes but does not have facial animations.


No intellisense with with Unity 5.5, Visual Studio Code integration, OSX 10.12.1 I get this with the listed software. It doesn't recognize object types and I can't use reference finding. I have the Omnisharp plugin installed and updated. Just wondering if this is supposed to work properly yet. I'm opening it with Assets Open Project In Code.


A scriptManager (singleton) not storing a variable (in the same scene) The script below is called every time I pickup an item and stores an instance of it in the array "mainInventory". The problem is when I access the array after picking up another item its empty. The script is on the MainCamera. public class InventoryManager MonoBehaviour public static InventoryManager instance null public Image inventoryPanel0 public Image inventoryPanel1 public Image inventoryPanel2 public Image inventoryPanel3 public Image inventoryPanel4 public Image inventoryPanel5 public Image inventoryPanel6 private Item mainInventory Use this for initialization void Awake () Singleton if (instance null) instance this else if (instance ! this) Destroy(gameObject) mainInventory new Item 7 public void pickedUp(Item item) Below checks which slot item belongs in bool positionFound false int currentPositionCheck 0 while (!positionFound) if (mainInventory currentPositionCheck null) positionFound true else currentPositionCheck Adds item to slot mainInventory currentPositionCheck item Adds image to inventory panel switch (currentPositionCheck) case 0 inventoryPanel0.sprite item.icon break case 1 inventoryPanel1.sprite item.icon break case 2 inventoryPanel2.sprite item.icon break case 3 inventoryPanel3.sprite item.icon break case 4 inventoryPanel4.sprite item.icon break case 5 inventoryPanel5.sprite item.icon break case 6 inventoryPanel6.sprite item.icon break default Debug.LogError("Expand inventory", this) break Item public class Item MonoBehaviour public string name public Sprite icon private MessageManager messageManagerScript private InventoryManager inventoryManagerScript private bool inRange private void Start() Gets managers GameObject managerContainer GameObject.FindWithTag("MainCamera") if (managerContainer ! null) inventoryManagerScript managerContainer.GetComponent lt InventoryManager gt () messageManagerScript managerContainer.GetComponent lt MessageManager gt () else Debug.Log("Can't find camera containing maangers") Update is called once per frame void Update() If in range and player presses key if (inRange amp amp Input.GetKeyDown(KeyCode.F)) Destroy(gameObject) OnTriggerExit(new Collider()) Pickup item inventoryManagerScript.pickedUp(this) private void OnTriggerEnter(Collider other) inRange true Displays pickup message if (other.gameObject.tag "Player") messageManagerScript.displayPickupMessage(name) private void OnTriggerExit(Collider other) Removes pickup message messageManagerScript.removeDisplayMessage() inRange false


Using Unity built in sprites programatically I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together. panelImage.sprite UnityEditor.AssetDatabase.GetBuiltinExtraResource lt Sprite gt ("UI Skin InputFieldBackground.psd") panelImage.sprite Resources.GetBuiltinResource(typeof(Sprite), "Resources unity builtin extra Background.psd") as Sprite The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?


How can I create light shafts like Journey's in Unity? I'd like to create cartoon looking sun light shafts that look very close (or identical) to the ones in very well known and loved games like Journey and Ori How can I accomplish this?


Are there game engines like Unity but for 2D? I really like the convenience of unity3d. The ability to edit the level and see my results in real time are great. My problem is the idea I want to implement is 2d and uses 2d sprites. Scaling sprites appears to be a problem for me and all advice I receive says to purchase 150 dollars addons for unity. I love the physics components and the rapid prototyping but I figured that maybe unity is not the tool for the job for this 2d game. Is there any 2d game engine like unity but for 2d games that would work on the PC and Android? Or is this something most people code themselves and make? To me the most important features of Unity3d were its ease to see what was edited and then have it apply instantly. Thank you. Most searches seemed to give me frameworks and not a large engine suite.


Mirror problems after building game in unity Hi I am facing a weird problem in unity when I build a particular scene. Here is the screenshot of how the mirror looks when I play the game from inside the unity editor And here is how it looks once I build this scene and then play it The quality settings at Edit Project Settings Quality are these And the player settings at File Build Settings Player Settings are these So how do I fix this? What do I need to change or is there any other entity?


How to line up rigidbody velocity with speed of moving floor So, I have a player who remains in the same X position. the floor moves from right to left underneath the player, and I am using tiles of 1 unit. Here's my jumping stuff if (RB.velocity.y lt 0) RB.velocity Vector2.up Physics2D.gravity.y (FallMultiplier 1) Time.deltaTime else if (RB.velocity.y gt 0) RB.velocity Vector2.up Physics2D.gravity.y (JumpMultiplier 1) Time.deltaTime if ( Input.GetKey(KeyCode.Space) amp amp IsGrounded amp amp JumpDelay lt 0) RB.velocity Vector2.up JumpVelocity JumpDelay 0.1f Debug.Log("Jumping") And here is what moves the floor Vector2 NewPosition TF.position NewPosition.x Time.deltaTime Speed TF.position NewPosition So, what I want to happen, is I have a movement speed for the floor, and I want to make it line up such that if I jump where the player is directly in the middle of one floor tile, they will land (say 4 tiles later) directly in the middle of another tile. I can get close by tweaking the velocities... but this feels the wrong way. I want to know what values I might be able to use, and how to calculate what velocities they should be. Speed of floor right now is at 5, Jump Multiplier at 1.75 and Fall Multiplier at 7. There of course do not line up as I hope, but it gives example values in case that helps. How would I solve this to say, for example, with the given multipliers, what should the floor speed be to line up perfectly?


Swipe Detection with mouse in Unity This is my swipe detection code. This code uses touch input. I want to do this using the left mouse button. So basically I want to 'swipe' using the mouse.How can I achieve that? public float maxTime public float minSwipeDist float startTime float endTime Vector3 startPos Vector3 endPos float swipeDistance float swipeTime Use this for initialization void Start () Update is called once per frame void Update () if(Input.touchCount gt 0) Touch touch Input.GetTouch(0) if (touch.phase TouchPhase.Began) startTime Time.time startPos touch.position else if (touch.phase TouchPhase.Ended) endTime Time.time endPos touch.position swipeDistance (endPos startPos).magnitude swipeTime endTime startTime if(swipeTime lt maxTime amp amp swipeDistance gt minSwipeDist) SwipeFunc() void SwipeFunc() Vector2 distance endPos startPos if(Mathf.Abs(distance.x) gt Mathf.Abs(distance.y)) Debug.Log("Horizontal swipe") else if (Mathf.Abs(distance.x) lt Mathf.Abs(distance.y)) Debug.Log(" vertical swipe")


How to fix this elbow issue when converting to humanoid Good day, how can I fix this? it looks fine in Blender and generic but not when I switch to humanoid. There is no error on rig tab but there are in animation tab under the import message that say quot is in between humanoid transforms and has rotation animation that will be discarded quot and I can't seem to fix it. Here are the things I've tried so far Put the right bones to the right slots. Enforce T pose. Translation DoF. Clicked Generate Retargeting and applied it.


How to "merge" multiple intersecting circles so that only the outer edges of each show? In my RTS (In Unity) each unit or building has strategic circles in a similar fashion to SupCom. If you have multiple units or buildings selected it looks like the picture to the left. I want to make it look like the picture to the right, where anything inside the outer edges of their circles is no longer shown. I draw these using vectrosity, mentioning this just in case vectrosity provides a way of doing this, or can be modified to do this. The circles are essentially just an array of points with lines drawn in between them. How would I go about "merging" the circles inside of their overlapping area? This is similar to How to make unit selection circles merge?, however I am not interested in a shader solution. Edit To re explain the above. I'm not seeing how the answers are applicable. I've read through the other thread before posting, which is why I posted it here to avoid this exact thing (being marked as a duplicate). I have an array of points with straight lines in between them to create a circle like effect. This is not a true circle, but a really granular polygon. I am interested in solutions that are achievable in C within Unity, not with shaders or with rendering mechanics. Edit2 Another picture based on one of Roberts suggestions This seems viable, though computationally expensive. If I have a circle made up of 250 points, and 50 circles all intertwined that's 615,500 checks in a worst case scenario.


Android Device Screen Flicker I have made sudoku type game. I am about to complete my game in 2d. At present, my game run smoothly on higher configuration devices such as Sony Experia Sola, Samsung Note 2 and Google Nexus. But it creates screen flickering problem in my HCL ME tablet. I don't what is problem going on. I notice that when I load prefabs then it start flickering problem. If I don't create any prefab then it don't flicker at all. At present my development game resolution is 2048x1536. So friends I need support from your side. If you want any more detail then I will provide any time.


How to best apply colliders on a rough 3D shape I have a 3D model for a level in unity. I want to add colliders to it. What is the best type of collider for this model? And,it is 3D


Teleport Not Working in Unity 2D So I'm basically trying to get my character to "use" a set of stairs by teleporting from one stairway door to another. Each stairway door will be paired with one other stairway door. Here's the code, I feel like it should be working...my Debug.Logs are even outputting the correct information. Also FYI, I have the Transform doorPairedWith as public so that I can just drag and drop the stairway door that each one is supposed to be paired with. using UnityEngine public class Stairs MonoBehaviour Player player public Transform doorPairedWith Vector3 doorPairedWithPosition Vector3 playerPosition BoxCollider2D playerCollider BoxCollider2D stairsTriggerCollider bool playerIsNearStairs false void Start() player Player.instance playerPosition player.transform.position doorPairedWithPosition doorPairedWith.position playerCollider player.GetComponent lt BoxCollider2D gt () stairsTriggerCollider GetComponent lt BoxCollider2D gt () void Update() UseStairs() void UseStairs() if (playerIsNearStairs true) if (Input.GetKeyDown(KeyCode.E)) Debug.Log("Attempting to use stairway door named " doorPairedWith) playerPosition doorPairedWithPosition void OnTriggerEnter2D(Collider2D collision) if (collision.gameObject.tag "Player") playerIsNearStairs true Debug.Log("Player is near stairs " playerIsNearStairs) void OnTriggerExit2D(Collider2D collision) if (collision.gameObject.tag "Player") playerIsNearStairs false Debug.Log("Player is near stairs " playerIsNearStairs)


How to change TPS camera angle in Unity I'm very new to Unity and this may simply be a failure of google fu but I hope someone here can help me out. I'm working through a series of tutorials on how to create an RPG in Unity, making small improvements and embellishments as I go to make sure I understand the concepts. I've built a player character with walk and run animations and a camera which follows the player around and stays aimed at the centre of the character model using the following code. using System.Collections using System.Collections.Generic using UnityEngine public class CameraFollowPlayer MonoBehaviour GameObject target Start is called before the first frame update void Start() target transform.parent.gameObject Update is called once per frame void Update() transform.LookAt(target.transform.position) The problem with this is the angle this leaves the camera pointing at in game is to acute, making it difficult to see what is ahead of the character. How can I adjust the target of the LookAt instruction to result in a shallower X axis rotation of the camera?


How to use an overlapping shader so that it uses layers sort from sprite renderer and its transparent Im using the shader from question , but once I put it in the game, and my character gets close to it, it will be hidden by the shadow of the tree, which is transparent. Any way to make the shader transparent and or maybe use the sprite renderer sort layer system I have been trying to use stencil configurable shader with no luck Thank you for your help Not sure what combination of these should work The character is using a normal sprite renderer.


Can't get the current animation state name (hash or .IsName) to work I have some hard times trying to get the current animation state name in Unity, to perform specific actions while I'm in a certain state. I want to know when I'm the "ThoughtsStill" state, I only have the default layer (Base Layer) To do this, here is what I tried AnimatorStateInfo curr state animator.GetCurrentAnimatorStateInfo(0) if (curr state.shortNameHash Animator.StringToHash("ThoughtsStill")) Debug.Log("I'm in ThoughtsStill state"). which is not working. I also tried with IsName() method but it is not working too (both tried to compare "Base Layer.ThoughtsStill" and "ThoughtsStill"). I'm certain that I'm going in this ThoughtsStill state but I don't know why I can't get it. Do you guys have any ideas or leads? Thanks !


Unity game debugging on Xcode This question has two parts 1. How to get meaningful information out of Xcode crash logs? The game runs fine on the editor but when running on an iOS device it crashes and then gives information like this How can I dig out which script actually causes this? 2. Which Xcode debugging tools are available for Unity games? There are plenty of them mentioned here. Especially the frame capture and Instruments profiling seem very handy.


Unity method framework for handling different input modes I'm a very new Unity developer who's looking for a best practice or framework for handling different input modes. I'm working in C . Here's a contrived example Sample Map Application Control Scheme 1 W A S D keys move map up right down left. Escape key closes application Spacebar opens menu and switches to Control Scheme 2 Control Scheme 2 W A S D moves menu selection up down into submenu back to parent menu. Escape key closes menu and switches to Control Scheme 1 I realize this is a silly contrived example, but it demonstrates the point. When we are in a menu we don't want the W A S D keys to also move the map while we are trying to navigate the menu. This could be done with a bunch of if statements such as if(moveMode) read keypresses and move map else if(menuMode) read keypresses and menu navigation But you can see how this would get messy very quickly if we had lots of modes. We could also end up with a lot of nested if statements if we have sub modes for controls. Surely there's a cleaner way to do this? Any best practices for this? Any frameworks?


Can a prefab of a complete Unity scene be created? Can we create a prefab out of a complete unity scene, so that we can instantiate the complete scene like we instantiate gameobjects in unity.


Dynamic model scaling Imagine a (3D) game like Railroad Tycoon 3. Player selects a rail track, clicks LMB and drags the mouse to the end position. During this drag, the rail track model scales and adopts to the landscape, so user sees the resulting track in dynamic. The question how this can be done? A brief idea links sketches will be enough. I just don't know how to start (I'm novice game developer). If it is matter, I use Unity as a game engine. Thanks in advance.


ECS Stats, damage types damage calculation Prologue Im quite new to data oriented programming and my goal is to implement a runescape stats damage mechanic. This is quite a pretty complex topic Runescape Mechanics 1 and i havent found any ECS related sources on that topic yet. In the following example we see a bunch of items which modify the weares stats based on a few conditions. This happens in two different variants, either for the damage calculation only, or as a buff. Brine sabre and Brackish blade increase damage against crabs. or Silverlight and Darklight increase ability damage by a scaling of 25 124 against most demons. The exact damage bonus is based on your base Attack and Strength, and the monster's base Defence. The problem Such a RPG system is very complex. There different damage types, different resistences and other stats. Having a strong OOP background and no real experience in DOP, i cant find a suitable architecture to fill those needs. In my current approach every stat is a component. Items and Buffs are structs. A item quot buffs quot its owner and the buff modifies his stats. This works so far, but i have no idea how i could realise the damage calculation, while still keeping it that flexible as it is in runescape. This little example would just be able to buff the stats... not deal, receive or modify the damage itself. The stats public struct Health float max float value public struct MeeleDamage float base float value public struct MeeleResistence float base float value Item amp Buffs public struct Item string name int amount bool equipable List lt Buff gt buffs public struct Buff string name float duration Condition applyable ToBuff stat float value Its also important that an entity can also deal damage to multiple other entities in one frame. How would you implement such an complex mechanic ? Any examples are appreciated !


Unity assets file structure I'm writing a map editor for a game built with Unity (5). I want to reuse as much of the resources from the game as possible. That means textures and meshes. I know they are somewhere in the assets files, but I need to be able to extract that data during runtime since I cannot (and do not want to) redistribute those files. Additionally, given that the game receives frequent updates, I need to be able to calculate the offsets each time the editor is started. I also need to know how the textures connect to the objects in the game. In order to do that, I need to know what the structure of assets file is, or at least find a way to extract them all and then use hex editor to figure out how they're put together. I know there is a devxdevelopment tool that can do the latter, but I don't really have any money to spend on this. Can you give me any info or pointers that would enable me to figure this out?


Should recoil be an animation or script? Should recoil for a rapid fire gun be be done through an animation or a script? I want the recoil to increase as I continuously fire, like a lot of FPS games do. I was initially considering achieving this through a script in unity that rotates the gun slightly each time I fire, but I realized that since I plan to have most rapid fire guns be 2 handed weapons, at some point, the left hand won't be on the weapon. However, since I also want the recoil to increase as I fire, I'm not sure how I can achieve this in an animation. How is recoil typically done? Input on this would be very much appreciated.


Why my charchter fluctuate instead go down stairs? My player is a capsule with First person controller Charchter controller When my player go up stairs, it works well. When my player go down stairs, it fluctuate in air. What am i wrong ? Thanks