How can i rotate the camera around an object, using compass? I want the camera to rotate around an object in Y axis, when you rotate your phone. how can i do this? i already have the code to do it using mouse, but i need it to turn with compass. here's the code for movement with mouse mouseX Input.GetAxis("Mouse X") offset (Quaternion.AngleAxis(mouseX cameraSpeed, Vector3.up) offset) transform.position point offset transform.LookAt(point) i know that setting the mouseX value to change with compass direction is my answer, but how can i do it?


Unity UV map, tint change color of texture I have an array of vertices with texture coordinates for a UV map in Unity newUV.Add(new Vector2 (0, 1)) FACE 1 newUV.Add(new Vector2 (1, 1)) newUV.Add(new Vector2 (1, 0)) newUV.Add(new Vector2 (0, 0)) newUV.Add(new Vector2 (0, 1)) FACE 2 newUV.Add(new Vector2 (1, 1)) newUV.Add(new Vector2 (1, 0)) newUV.Add(new Vector2 (0, 0)) mesh.uv newUV.ToArray() It textures my mesh just fine. How could I go around tinting FACE 1 to a darker color? Let's say the texture is just plain green and I wanted to texture only on FACE 1 to be a darker shade of green.


Food Game using Online Searchs I am thinking of making a simple game with Unity. The aim would be to keep a person healthy by feeding it well balanced food and drinks. Rather than hard codding every single type of food or drink I can think of I was thinking of letting the player choose any type of food he wants and then screen the internet for it's calorific value, saturated fat, sugars etc ... This would make the game much more enjoyable than being limited by the foods I can think of. I was wondering how you would go about doing that ? Could I use an API to extract data from google or wikipedia. I noticed that when you type " food calories" in Google you get a return from the Wikipedia page like this Obviously, there is a way of extracting the data from Wikipedia and I could automate the searchs by taking the player's entry as a string and running a search with it. How would one recommend going about this ? Also, is it safe ? Thanks


Can an iOS application have an explicit quit button? I've heard a rumor that you cannot have an explicit quit button on your app when it goes to the Apple App Store, can anyone verify this? It seems that most applications do not have one, and there is no explicit quit. How to developers handle quitting in general on iOS applications? Note I am using Unity, C , and Xcode to develop my game for the iPad.


How to make a car move sharper at high speed? I am working on a car racing game on Unity 2018.1. My car works perfectly at low speed but as it speeds up, I lose control over the car and it starts to drift independently. What can I do to prevent this?


Add object to a Terrain? It's possible to add object made by blender to unity terrain ? this object will become a part of it. I can add grass and trees on it.


How to achieve lighting like this in Unity for 2D games? How could I accomplish a lighting effect something similar to this game? I'm not talking about the shadows but about the glowing lighting effect on the crystals and the torches. Anyone got any clues? More images from the games steam page


Are all referenced sprites loaded into memory for each object? I'm trying to understand how Unity works behind the scenes. Let's say I have a GameObject that has a large number of sprites attached to it in an array (think a deck of cards). Each GameObject represents 1 card. For simplicity, each card has all the sprites for all the card faces. So it has 52 sprites 1 for the card back (all in a sprite sheet of course). If I have all 52 cards placed in the world. Does this mean I have 53 52 2756 sprites, or is there only one instance of each sprite that's being displayed (ie does it only use the resources of 52 active sprites)? I guess what i'm asking is if I have a bunch of sprites attached to a GameObject, are they all instantiated when the object is created, or are they only created when they are actually attached to the sprite renderer? Would it be more efficient to only attach the current cards value sprite (ie just the back and the face for the cards value)?


Unity 2D launch player towards mouse location few notes I'm new to game development I'm not new to developing (1 year of front end web development) I'm trying to get my character to launch towards mouse left click button (which I understood to be translated into screen onclick once its exported to mobile) I've got the following code down (used the web for help) move speed is a float that's equal to 10 in this example if (Input.GetMouseButton (0)) mousePosition Camera.main.ScreenToWorldPoint (Input.mousePosition) direction (mousePosition transform.position).normalized rb.velocity new Vector2 (direction.x moveSpeed, direction.y moveSpeed) Which works great, but has 2 issues If I keep holding leftMouseButton my character is pinned to the cursor I want a single, gravity affected, launch (jump of sort) towards my mouse button. This is all under the Update() function.


Simulating an aging population Introduction The main idea is to "classify population as they age". Let me further explain it with an example Example There are 50k population (we are not going to care about if male or female for now). Inside these number there are kids 0 16 , fertile 16 40 , non fertile 40 100 . Question Which would be a nice implementation to represent an evolving population data that is better or at least not too resource intensive as my example below? My Idea (Pseudo code) Population Array Age 0 gt 5 Array a pop obj that stores data Age 5 gt 10 pop obj . . . Age 95 100 pop obj This would be the structure and each tick happens this calculation FertilePop.count fertility rate (some other stuff) numberOfBirths where numberOfBirths are added to the Age 0 5 .obj.count and the rest of Age rang are subtracted a number and added onto the next Age rang until Age 95 100 where they "die of old age". Notes This is purely background data and i am asking for a better solution implementation that could be less complex, more dynamic and learn from it. I expect to be able to do a graph plot so the user sees the pop evolution. I took my interest in the matter from this link here to a population simulator. https niko.roorda.nu computer programs popsim population simulation Thanks for your interest in this question.


Get all objects of Additively loaded Scene? (LoadSceneMode.Additive) I learned how to Load and unload scenes in unity. using LoadSceneMode.Additive. I like to spit up my scenes as much as possible and retain the stuff I need as I go along. I'd like to be able to find all objects loaded from a specific scene. Obviously Unity knows but I can't find how to get them. For now, my workaround is to put them in a specifically named empty or have them tagged in a certain way, but that is a workaround. Is there an easier way?


Check which Player got highest Number from Dice I am doing a Ludo Game and currently i need to check which Player got the Highest Number from the Dice and the player which has the highest number goes on the starting position. Currently i created this method to check which player got the highest number then the player which has the highest numbers runs the method MovePlayer() public void FirstTurn() player1Steps GameObject.Find("Player1").GetComponent lt LevelManager gt ().randomNumberSteps player2Steps GameObject.Find("Player2").GetComponent lt LevelManager gt ().randomNumberSteps if(NetworkManager.MyGamePlayerId "Player1" amp amp player2Played true) MovePlayer() else if(NetworkManager.MyGamePlayerId "Player2" amp amp player1Played true) if(player2Steps gt player1Steps) MovePlayer() I am using the Photon Cloud Service since this is a multiplayer Game Thanks


Check if all gameobjects are destroyed I am making a shooting game, where I have a countdown as I destroy enemies. I want to implement logic when all the game objects are destroyed within the given time, and the countdown reaches zero. How do I do that?


How do I keep vertex position when changing material? I've created 2 shaders using shader graph which I'm applying to a sphere to simulate a ball of water ice. The water shader distorts the shape of the sphere over time to look like it's flowing a bit. What I would like to do is swap the shader from water to ice, and keep the shape of the distorted sphere when the materials swap over. I'm pretty new to unity and shaders in general so I don't know where to start.


2 D character not falling to the ground I am very new to Game Development and I am making a game with a simple Ragdoll which has a body, a head, and 2 limbs(hands). The head and the limbs are hinged to the body and I have kept the Ragdoll above a cube to be used as the ground on which the Ragdoll falls. Till now, I haven't added any scripts for movement or anything, I just want my Ragdoll to fall on the cube below it properly. But when I click play, the Ragdoll just starts to float above its original position. When I move it through the editor away from the cube(ground), it does fall down. It's like the cube is opposing the downward acceleration of the Ragdoll. The Ragdoll won't land on the cube. All the bodies have Rigid body and collider scripts. The Ragdoll also doesn't disassemble, it manages to keep itself together. Can someone please tell me what I am doing wrong. I researched about this but I have found no solution. I am using the free version of Unity.


Jumping onto higher ground Collider issues What's the general solution to the following character animation problem (I'm using Unity)? You have a character with a capsule collider and a jump animation that allows you to jump onto higher ground (such s boxes, etc.). The character shouldn't be able to jump unrealistically high so she goes into a crouched posture while in the air and the collider is scaled accordingly in an animation curve. However when the character jumps onto the box to land, the character animation (and collider) want to extend back to wards the ground but there is not enough space and either collision detection fails and the character falls into the geometry or the collider starts a collision fight with the box and keeps bumping up and down, keeping the character in an airborne state. Please see screenshots to get a better idea... What would be a good way to work around this problem?


Stopping player from spamming movement keys which causes glitches Unity C I wrote a script for the player movement in c . Whenever the player presses A or D, it moves him her to the left or right by 12 units and when the player presses W or S, it moves him her up or down by 12 units. My script works fine, but if a person starts to spam all of the keys at once, it glitches out and the player object is not in line with the level anymore. I want to have the script check if there a movement is currently happening before executing the movement on the keypress. Here is my script void Update () transform.Translate(Vector3.forward ForwardSpeed Time.deltaTime) if (Input.GetKeyDown (KeyCode.A) amp amp side gt maxSideLeft) MoveObjectTo(this.transform, new Vector3(this.transform.position.x 12, this.transform.position.y, this.transform.position.z 10), movementSpeed) side 1 else if (Input.GetKeyDown (KeyCode.D) amp amp side lt maxSideRight) MoveObjectTo(this.transform, new Vector3(this.transform.position.x 12, this.transform.position.y, this.transform.position.z 10), movementSpeed) side 1 if (Input.GetKeyDown (KeyCode.W) amp amp level lt maxLevelHeight) MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y 12, this.transform.position.z 10), movementSpeed) level 1 else if (Input.GetKeyDown (KeyCode.S) amp amp level gt minLevelHeight) MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y 12, this.transform.position.z 10), movementSpeed) level 1 if (Input.GetKeyDown (KeyCode.R) Input.GetKeyDown(KeyCode.Space)) SceneManager.LoadScene ("Scene1") Time.timeScale 1 private void MoveObjectTo(Transform objectToMove, Vector3 targetPosition, float moveSpeed) StopCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed)) StartCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed)) public static IEnumerator MoveObject(Transform objectToMove, Vector3 targetPosition, float moveSpeed) float currentProgress 0 Vector3 cashedObjectPosition objectToMove.transform.position while (currentProgress lt 1) currentProgress moveSpeed Time.deltaTime objectToMove.position Vector3.Lerp(cashedObjectPosition, targetPosition, currentProgress) yield return null


Redundant checks from spatial partitioning A simple 2D grid partition system for collision detection divides space into equal sized tiles. Colliders then map themselves to tiles with their bounding box in O(1) time. Collision detection only has to be performed between objects that occupy the same tile(s). Collision detection is expensive so the more culled, the better. With a grid partitioning system, how are collisions culled when colliders share multiple tiles? For example, Circle A and Circle B both sit on the edge between Tile 1 and Tile 2. Iterating both tiles would make collision detection between Circle A amp Circle B run twice. A global pair hashtable seems performance expensive since it has to be cleared every frame. Tracking pairs inside colliders takes a lot of memory. How do you mitigate redundant pairs when iterating through partition grid tiles?


Lock mouse in center of screen, and still use to move camera Unity I am making a program from 1st person point of view. I would like the camera to be moved using the mouse, preferably using simple code, like from XNA var center this.Window.ClientBounds MouseState newState Mouse.GetState() if (Keyboard.GetState().IsKeyUp(Keys.Escape)) Mouse.SetPosition((int)center.X, (int)center.Y) camera.Rotation (newState.X center.X) 0.005f camera.UpDown (newState.Y center.Y) 0.005f Is there any code that lets me do this in Unity, since Unity does not support XNA, I need a new library to use, and a new way to collect this input. this is also a little tougher, since I want one object to go up and down based on if you move it the mouse up and down, and another object to be the one turning left and right. I am also very concerned about clamping the mouse to the center of the screen, since you will be selecting items, and it is easiest to have a simple cross hairs in the center of the screen for this purpose. Here is the code I am using to move right now using UnityEngine using System.Collections AddComponentMenu("Camera Control Mouse Look") public class MouseLook MonoBehaviour public enum RotationAxes MouseXAndY 0, MouseX 1, MouseY 2 public RotationAxes axes RotationAxes.MouseXAndY public float sensitivityX 15F public float sensitivityY 15F public float minimumX 360F public float maximumX 360F public float minimumY 60F public float maximumY 60F float rotationY 0F void Update () if (axes RotationAxes.MouseXAndY) float rotationX transform.localEulerAngles.y Input.GetAxis("Mouse X") sensitivityX rotationY Input.GetAxis("Mouse Y") sensitivityY rotationY Mathf.Clamp (rotationY, minimumY, maximumY) transform.localEulerAngles new Vector3( rotationY, rotationX, 0) else if (axes RotationAxes.MouseX) transform.Rotate(0, Input.GetAxis("Mouse X") sensitivityX, 0) else rotationY Input.GetAxis("Mouse Y") sensitivityY rotationY Mathf.Clamp (rotationY, minimumY, maximumY) transform.localEulerAngles new Vector3( rotationY, transform.localEulerAngles.y, 0) while (Input.GetKeyDown(KeyCode.Space) true) Screen.lockCursor true void Start () Make the rigid body not change rotation if (GetComponent lt Rigidbody gt ()) GetComponent lt Rigidbody gt ().freezeRotation true This code does everything except lock the mouse to the center of the screen. Screen.lockCursor true does not work though, since then the camera no longer moves, and the cursor does not allow you to click anything else either.


Unity Odd distortion on default material cube Does anyone know what causes this strange effect that looks like ripples? This is simply the default material on a cube and should be perfectly smooth. (Clear example at top right of image) Another example


Unity font API behaves differently in built game Specifically it's Font.CreateDynamicFontFromOSFont(), use this script attached to an empty GameObject in the scene. using System.Collections using System.Collections.Generic using UnityEngine public class TestFontTexture MonoBehaviour void Start () var font Font.CreateDynamicFontFromOSFont("Consolas", 12) font.RequestCharactersInTexture("HelloWorld", 20) SaveTexture2PNG(". fontTexture.png", (Texture2D)font.material.mainTexture) void Update () void SaveTexture2PNG(string path, Texture2D tex) byte bytes tex.EncodeToPNG() System.IO.File.WriteAllBytes(path, bytes) After click play it should create a fontTexture.png file containing character glyphs in the Assets folder, but only in editor though. In the built game it just created a completely black image. Since it's OS concerned, I'm using Windows 7 with font Consolas installed and Unity 5.6.5f. How to make it work in a built game?


How to only allow one space in an InputField? I've been messing with this for a while now and I can't get this to work 100 . I'm using an InputField for players to enter a character name, and I want to allow a first and last name. Here's how I've been trying this private void CharNameRestrictions() Debug.Log(spaceCount) if (Input.GetKeyUp(KeyCode.Space)) spaceCount if (spaceCount gt 1) spaceCount 1 playerNameInput.text playerNameInput.text.Remove(playerNameInput.text.Length 1) if (!(playerNameInput.text.Contains(" "))) spaceCount 0 if (playerNameInput.text.Length gt 15) playerNameInput.text playerNameInput.text.Remove(playerNameInput.text.Length 1) This sort of works, but if you press and hold space while typing another character, it still lets you add additional spaces. Is there a way to simply ignore the space keycode when there is already a space in the field?


Unity Debug UnityGfxDeviceWorker (34) EXC RESOURCE RESOURCE TYPE MEMORY Unity How does one debug this Xcode error on an iOS device? Debug UnityGfxDeviceWorker (34) EXC RESOURCE RESOURCE TYPE MEMORY


AddRelativeForce not working correctly I am stuck on the code for couple of days but couldn't figure it out. Therefore I turned out to look the answer here but couldn't find any that match the requirement Hope some One might help here is the code Part1 Step Horizontal Movement Use to get left and right movement if(Input.GetKey ("right") Input.GetKey ("left")) moveDir.x Input.GetAxis("Horizontal") get result of AD keys in X rigidbody.velocity moveDir speed Part2 Continuse Forward Movement if (Input.GetKey(KeyCode.UpArrow) Input.GetKey(KeyCode.W)) moveDir.z Input.GetAxis("Vertical") rigidbody.AddRelativeForce(moveDir 50) I have a Cube with added rigidBody Component. When pressed left or right key the cube should move in that direction and when key is released it should stop Part one when run commenting part2 code runs correctly the other movement that I am trying to achieve is the cube should move continuously.But the thing is when pressed up key it should increase the magnitude and when released it should maintain the magnitude and move constantly.This is also achieved successfull with the part2 code by commenting part1 code But when but run without commenting any of them part1 results are correct but part2 does not provide correct result which was obtained by commenting part1 code Is there any other way to obtain the same reult


How to check audio quality after changing import settings I have changed the quality of an audio clip from 100 to 10 in the import settings. But when I played the clip from the inspector, I didn't hear any noticeable difference The compression format of the audio clip is set to 'Vorbis' So I wonder if it's the original file or the compressed file that is being played by the Unity Editor?


Follow Camera to Two objects at different time I am developing simple 2D game in unity. I am locked with the camera movement for last two days. I've camera script that is working as follows Follow the player to X and Y direction If player stops moving, Camera must find the nearest enemy and should move to that direction Both of the above function works fine, but separately. Camera finds and follows the enemy, when there is no input from player for last 10 seconds. But after few seconds (When stops following enemy), Camera retains the player's position. That creates unlikely effect in the scene. I want the camera to have a last position and started following player from there. For your reference I'm writing my Camera Script. public class MultipleTargetCamera MonoBehaviour public List lt Transform gt targets ReadOnly public GameObject closestEnemy null public EnemyController closestEnemyController null public Vector3 offset public float smoothTime 0.5f private Vector3 velocity Vector3 camPosition Update is called once per frame void LateUpdate() if (targets.Count 0) return if (!TheGlobals.instance.movingTowardsEnemy) MoveCamera() else MoveAsEnemy() void MoveAsEnemy() camPosition new Vector3(transform.position.x closestEnemyController.xDiff, transform.position.x closestEnemyController.yDiff, transform.position.z) transform.position Vector3.SmoothDamp(transform.position, camPosition, ref velocity, smoothTime) void MoveCamera() Vector3 centerPoint GetCenterPoint() Vector3 newPosition centerPoint offset transform.position Vector3.SmoothDamp(transform.position, newPosition, ref velocity, smoothTime) Vector3 GetCenterPoint() Vector3 targetPos new Vector3(targets 0 .position.x, targets 0 .position.y, transform.position.z) if(targets.Count 1) return targetPos var bounds new Bounds(new Vector3(targets 0 .position.x, targets 0 .position.y, transform.position.z), Vector3.zero) for(int i 0 i lt targets.Count i ) bounds.Encapsulate(new Vector3(targets i .position.x, targets i .position.y, transform.position.z)) return bounds.center public void FindNearestEnemy() GameObject gos gos GameObject.FindGameObjectsWithTag("Enemy") float distance Mathf.Infinity Vector3 position transform.position foreach (GameObject go in gos) Vector3 diff go.transform.position position float curDistance diff.sqrMagnitude if (curDistance lt distance) closestEnemy go distance curDistance closestEnemyController closestEnemy.GetComponent lt EnemyController gt () targets 0 .parent this.transform StartCoroutine(StopMovingTowardsEnemy()) IEnumerator StopMovingTowardsEnemy() yield return new WaitForSeconds(0.01f) TheGlobals.instance.movingTowardsEnemy false I hope I did explain well. Looking for the answer. Thank you in advance!


Why does the player grab the object outside the trigger zone? I want the player to be able to grab an object (in this case the knife) when he is in the object's trigger zone. He can get the knife but there is a problem if I press grab button outside of the trigger zone, then he can get the knife immediately after entering the zone. I want Unity to get the input only when the player is in the trigger, otherwise it should not be working. Here's the grab script using System.Collections using System.Collections.Generic using UnityEngine public class Grab MonoBehaviour public GameObject player private bool grabbed public GameObject knifePosition private bool isInTrigger void Update() if (Input.GetButtonDown( quot Grab quot )) grabbed true else grabbed false if (grabbed amp amp isInTrigger) gameObject.transform.position knifePosition.transform.position private void OnTriggerEnter2D(Collider2D collision) if (collision.gameObject player amp amp grabbed) gameObject.transform.SetParent(player.transform) isInTrigger true Debug.Log( quot Picked up quot )


"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?


Player rotation issues (Player returns to default forward rotation after releasing keys) So basically what is happening is that my player rotates and faces the direction that he is currently being steered toward (which is wonderful). But after I release, let's say the A key, meaning he is currently facing and moving to the left, he goes back to facing forward after the key is released. Here is my code public class PlayerMovement MonoBehaviour public bool isGrounded private float distToGround private Vector3 v private Vector3 h public float speed Rigidbody rb Collider col void Start() rb GetComponent lt Rigidbody gt () col GetComponent lt Collider gt () distToGround col.bounds.extents.y void Update() if (Physics.Raycast (transform.position, Vector3.up, distToGround 0.1f)) isGrounded true else isGrounded false if (isGrounded) v new Vector3(0, 0, Input.GetAxis("Vertical")) speed h new Vector3(Input.GetAxis("Horizontal"), 0, 0) speed rb.MovePosition(rb.position v Time.deltaTime) rb.MovePosition(rb.position h Time.deltaTime) This deals with all the rotation Vector3 direction new Vector3( Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical") ) Quaternion rotation Quaternion.LookRotation(direction, Vector3.up) transform.rotation rotation I obviously know that the reason this is happening is because the rotation is being set to the axis currently being pressed, so when I release any key, the rotation goes back to the original position. I just can't quite figure out how to fix it...


Could use some help figuring out bouncy physics material in this PhotonEngine game So I'm trying to prototype a primitive 1v1 fighting game where the goal is to push the opponent off of the platform rather than actually fight. This is working great in a local multiplayer setup using a physics material on the "belly" of the Rigidbody2d players (the circle collider gameobject nested inside of the square gameobject has the bouncy material). But I'm toying with the idea of making it a network game and it seems the physics material doesn't get communicated too well over the Photon Realtime connections? Here is a video showing how it seems like sometimes the position is updated but sometimes a player runs into another player and its like a brick wall https imgur.com QYWH178 Any ideas of what to try or if this is even possible? A bit about how things are currently setup Each player object has the nested collider with a high bounciness material on it. Each player moves via the Rigidbody2D component via .AddForce(direction Speed) I have a Photon View component on the player prefab and a Photon Rigibody 2D View component that is checked to Synchronize Velocity and Angular Velocity, as well as a Photon Transform View component synchronizing Position. Both the transform view and Rigidbody2dView are Observed Components in the Photon View. I also found a script someone posted where they were manually sending the position velocity data via OnPhotonSerializeView() I've tried adding that script and making that observable as well, but no luck, but it looks something like this public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.IsWriting) We own this player send the others our data stream.SendNext(transform.position) stream.SendNext(transform.rotation) stream.SendNext(r.velocity) stream.SendNext(r.angularVelocity) else Network player, receive data latestPos (Vector3)stream.ReceiveNext() latestRot (Quaternion)stream.ReceiveNext() velocity (Vector2)stream.ReceiveNext() angularVelocity (float)stream.ReceiveNext() valuesReceived true Update is called once per frame void Update() if (!photonView.IsMine amp amp valuesReceived) Update Object position and Rigidbody parameters transform.position Vector3.Lerp(transform.position, latestPos, Time.deltaTime 5) transform.rotation Quaternion.Lerp(transform.rotation, latestRot, Time.deltaTime 5) r.velocity velocity r.angularVelocity angularVelocity


Using raycast to detect whether a wall immediately blocks a player in Unity C I am working on a game project of which involves a procedurally generated maze. Within this maze, there are different types of tiles, such as walls and gates. I want to program the player so that it cannot move through a tile that is tagged as a "wall", and I am hoping to use ray casting to detect item tags. Now, you may think it would be simpler to use rigid bodies, but the game is set up so that the player moves 1 unit per movement, instead of being able to move at any randomly input distance, in order to keep the game adhering to a "grid" for the sake of other events that happen within the game. So, for this reason, i wish to detect if a wall is north of the player (let's call "north" as "up", as I have an "up blocked" boolean to state if a wall is directly "north" of the player) but, my code doesn't always recognise walls that are immediately north of the player, and instead sometimes the "up blocked" boolean becomes activated as "true" when a wall is left, right, or "below" (down) of the player, irrespective of whether or not there is a wall "above" or down. here is my code Vector2 vUp new Vector2(transform.position.x, (transform.position.y 0.05f)) RaycastHit2D hitUp Physics2D.Raycast(transform.position, vUp) if (hitUp.collider ! null amp amp hitUp.collider.tag "wall") upBlocked true else upBlocked false I have spent many hours looking for a solution for this problem, but most mediums provide information that either didn't work, wasn't applicable or simply was grossly out of date.


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.


timeScale 0 doesnt stop all prefabs in unity As expected timeScale 0 can be used for stopping the game or pausing but when i make timeScale equal to 0 some prefabs still move and they can shoot bullets but addforce doesnt effect to bullets and they stop there. I know i can fix the problem on handling code of my prefabs but they are a lot. is there a good way to do the trick in my game? thank you for helping


Split a region into arrays based on point region I have an array of points forming a grid. I want to split this array into multiple arrays that each contain a region of point. Let's say each point as a value like on this image The points having the same value and being connected would go into the same array. If it was only an array of all the 8 or all the 7, it wou d be easy, but in thsi case I need the arrays to contain connected equal values. For example, the purple region of 1 would make an array, the 8 region on the left would make an array and the one on the right too, but a different one. I just don't know how to use a loop to navigate in the grid and affect each point to an array based on they relation with other points of the same value. As this is the objective, think of the values as biome that I want to assign to an array.


2D player controller moves to the left, but not to the right I wrote a C script to control a 2D player, but the script is not fully working. When I press the right arrow d key to move the player is not moving in the right direction, but I have done the same exact thing for left key which works fine.The script shows no errors too.Kindly help me to solve the issue.The code is using UnityEngine public class PlayerController MonoBehaviour SerializeField private Rigidbody2D rb2d SerializeField private float speed SerializeField private float jump private static float tempspeed private static float tempjump private bool isRight private bool isLeft private bool isSpace private void Start() isLeft false isRight false isSpace false speed 5f jump 7f tempjump jump tempspeed speed private void Update() ReadInput() private void FixedUpdate() Move() private void ReadInput() if (UnityEngine.Input.GetKey("d") UnityEngine.Input.GetKey("right")) isRight true else isRight false if (UnityEngine.Input.GetKey("a") UnityEngine.Input.GetKey("left")) isLeft true else isLeft false if (UnityEngine.Input.GetKey("w") UnityEngine.Input.GetKey("up")) isSpace true else isSpace false private void Move() Vector2 speedVectorRight new Vector2( tempspeed, rb2d.velocity.y) Vector2 speedVectorLeft new Vector2( tempspeed, rb2d.velocity.y) Vector2 jumpVector new Vector2( rb2d.velocity.x, tempjump) if ( isRight) rb2d.velocity speedVectorRight else speedVectorRight.x 0f rb2d.velocity speedVectorRight if ( isLeft) rb2d.velocity speedVectorLeft else speedVectorLeft.x 0f rb2d.velocity speedVectorLeft if ( isSpace) rb2d.velocity jumpVector When I tried to print debug statements in different parts of if statements, they work fine. The problem in my observation is in if ( isRight) rb2d.velocity speedVectorRight else speedVectorRight.x 0f rb2d.velocity speedVectorRight The rb2.velocity is not accepting speedVectorRight I guess.Thanks in advance!


How can I disallow the changing of a parent? I want to disable transform.SetParent(Transform) for a particular GameObject. I am not sure where to start, so it is really difficult to show what I have tried. Is this even possible?


Make a platform appear and disappear constantly I am building a platformer. In this game, I need one of my platforms to constantly activate and deactivate. Here is how I have tried to code this so far, but it causes Unity to freeze void Update() for (i 0 i lt 2 i ) platform.SetActive (false) if (i gt 1 ) i platform.SetActive (true)


How to properly copy paste object between folder? I'm new to unity and found some simple task can't be done here. For example in projects tab, i want to copy paste a script from script folder to other folder. I should be able to simply select the script, press ctrl C , go to target folder , press ctrl V to paste but nothing happen. So for now , i have to duplicate it then move it to new folder then rename it. But why can't i do simply copy and paste ?


Prevent showing movie files after packaging unreal game I developed a game which has some videos inside it. I added videos into my project folder so that I can access them. After packaging, on the folder all videos will be shown as its original format which everyone can play it. How is it possible on release version no one can go to game folder and play it? Maybe some kind of encryption or change format of file which only its game can play it would help it. For example when you have a game on your computer, the only way to see the video is that you play the game and you will see relevant videos in the right time. However, after packaging, all videos will be on a folder any everyone can go to the folder and play it and see videos even without playing game. In Unity after releasing the game, you can't access assets, it will be shown in a file with .resource extension so no one can access it. However, in Unreal Engine, it will show the real file.


how to recieve a trigger with collider or recieve a trigger with collider in unity i know if your object has a Collider you can sense another Collider with OnCollisionEnter function or... and you can sense another collider with trigger with OncollsionEnter function and... but i want to sense other object with trigger even with collider or even with trigger. i cant sense otherobjects that have triggers. for example i have bullet that as i dont want to collider have any physics i turned it to trigger but how can make a charcter to sense it? Thank you for helping


(2D) Take player speed into account while shooting bullets In my top down 2D game, there is a plane as shown below The plane shoots bullets forward. For firing bullets, I use obj.GetComponent lt Rigidbody2D gt ().AddForce(transform.up 500) However, when player presses up arrow or A key, plane speed increases. At this point, bullets are slower than the plane and appear to move backwards when plane moves at maximum speed. How do I take into account player speed so that force applied takes into account player speed?


How to mark a variable as prefab independent? I am making a game that has a symmetrical level design. Each player own a portion of the map and each portion is the same. As such, I placed the portion as a prefab so that when I apply the prefab, every other portion gets changed as well. On the prefab there is a script. This script contains a variable called playerId. I dont want this variable to change to prefab default when I apply the prefab. Is there an attribute tag I can use to do this? As far as I am aware, Unity's transform.position doesnt get affected by the prefab defaults.


No intellisense on my classes I've been using Monodevelop's current version and Unity 4. I don't get intellisense on the classes I've created but I do have intellisense on classes that are in Unity's framework. Bug or its just as it is? I use UnityScript class SomeClass extends ScriptableObject public function Test() return "" In another class, when I use a variable typed as this class I get no intellisense.


Using AR measuring techniques to allow free movement in a VR room I am a Game Design student currently working on my graduation project. For this project, I want to develop a VR room, which can be walked through freely by using a smartphone. I already made a 1 1 scale replica of a meeting room (in Unity 3D) in the office I am currently working. So I have been exploring different technologies that allow distance measuring techniques using markers and AR applications to measure distance between physical objects. for example https www.youtube.com watch?v Tk31uGo7xHo https www.ourtechart.com augmented reality augmented reality tutorial 47 shapes combined trackers unity3d vuforia Now is it possible to use these methods to translate the measured distance into a vector 3 movement in a VR room? Also, is this relatively easy to do for a beginner programmer? To be clear The goal is to allow free movement through a pre built 1 1 scale 3D room in VR by using a smartphone and markers in the physical room. Which hopefully will create some cool VR experience for the players. Could anyone give me some advice? For example is there anyone who already tackled this problem and is willing to share knowledge with me? Thanks in advance


Mechanim "Hand Closing Opening" Animation control with trigger I wish to control any given Animator state "Playhead", with a variable rather than have it play automatically with time. This is for an animation of a hand making a "clench gesture" which will be bound to an analog controller trigger output value. I have considered the following Inside StateMachineBehaviour.OnStateUpdate method (State machine behavior script attached to a state in the Mechanim graph) Call Animator.Play or Animator.CrossFade to play a given clip from a given time with speed set to 0. This should get called every update while in the state. The issue with this is that the whole state will stop, then start again which means OnStateEnter and OnStateExit continually fire, rather than just the OnStateUpdate method to control the "Playhead". Animator.ForceStateNormalizedTime(time) This would be fine but it has been depreciated. Use timers and the Animator speed variable to calculate when to toggle playing a clip at a certain speed such to match the displacement of the trigger. Seems the wrong way to go about it. Use the legacy animation system This works fine but you don't get the perks of Mechanim FSM eg. blend trees. Since Unity seem to have removed the ability to manipulate the time of a running clip or Mechanim state, it makes me think it's something I shouldn't be doing. Am I going about this the wrong way? Why does it seem difficult to play an animation via something other than the time domain?


2d raycast collision problem I am currently making a 2d top down game in unity and have stumbled upon a problem with my raycast collision. I want my green player to stop moving when colliding with a wall, therefore i made my player object cast a ray in the direction it is moving. Its velocity is nullified when the distance to the collision point is equal to zero, or below. What seems to be the case is that the player object stops moving way to late and ends up overlapping the wall object. I tried to make an offset such that the player stopped a bit earlier, but it seems that the offset needs to differ depending on the side of the wall block. It even feels like the point at where the player stops is arbitrary and differs from time to time. I would really like to know why this happens and what i can do to fix it. BTW, I would also really like to be able to change the players speed and still have it work. Here are some pictures of my problem The code i use for the player using UnityEngine using System.Collections public class Player MonoBehaviour SerializeField private float speed Rigidbody2D body bool justChangedDir Vector2 moveDir void Start() body GetComponent lt Rigidbody2D gt () void MoveDirection() Vector2 input new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) if ((input.x ! 0 amp amp input.y 0) (input.x 0 amp amp input.y ! 0)) justChangedDir false if (moveDir.x ! 0) moveDir new Vector2(input.x, 0) if (input.y ! 0 amp amp !justChangedDir) moveDir new Vector2(0, input.y) justChangedDir true else if (moveDir.y ! 0) moveDir new Vector2(0, input.y) if (input.x ! 0 amp amp !justChangedDir) moveDir new Vector2(input.x, 0) justChangedDir true else moveDir input void CheckCollision() RaycastHit2D hit new RaycastHit2D() if (moveDir.x ! 0) hit Physics2D.Raycast(body.position, Vector2.right moveDir.x, 1) Debug.DrawRay(body.position, Vector2.right moveDir.x, Color.yellow) else if (moveDir.y ! 0) hit Physics2D.Raycast(body.position, Vector2.up moveDir.y, 1) Debug.DrawRay(body.position, Vector2.up moveDir.y, Color.yellow) if (hit.collider ! null amp amp hit.distance lt 0.5 ) body.velocity Vector2.zero else body.velocity moveDir speed Update is called once per frame void Update() MoveDirection() if (moveDir ! Vector2.zero) CheckCollision() else body.velocity Vector2.zero Any help will be really appreciated ) Many thanks in advance! Gusgus


Code for making Material offset follow Bone transform not exactly working In my game, I have an Eye Bone that is constantly moving. I'm trying to make a material attached to the eye (pupil material) move in relation to the Eye bone's transform. This Script is indeed moving the Material's offset, but it is seemingly ignoring the offsetMultiplier bit. For instance, if I set offsetMultiplier to 0, the material offset never equals 0 but instead keeps exactly following the Bone transform numbers. What might be the mistake here? using System.Collections using System.Collections.Generic using UnityEngine public class EyeBoneMatOffset MonoBehaviour public Transform targetBone public Material mat public float offsetMultiplier 0.0f 0 for testing purposes Start is called before the first frame update void Start() Update is called once per frame void Update() Create a vector to offset the material var offset new Vector2(targetBone.transform.localRotation.eulerAngles.x offsetMultiplier, targetBone.transform.localRotation.eulerAngles.y offsetMultiplier) Apply the offset mat.mainTextureOffset offset Script inspector set up Edit I'm having issues getting the Eye(Pupil) Material to correctly move with the Eye bone movement. You can see that when I hit play, the script does get the Eye Material to Initially move, but then it is (visually) frozen instead of moving back and forth. The goal is for it to correctly Eye Track the cube. As a sidenote, for the Eye Material's X and Y offset, the visually correct range of its pupil movement is 0.45 to 0.45 (X), and 0.45 to 0.45 (Y). So it's weird to me that the X and Y offset of the Eye Materials are shown to be moving within that range (which should be good!), yet are not actually moving visually except for when the game first starts.


Unity baked lighting blotchy shadows, bleeding and or stiching I have spent days trying to get baked lighting to look good. I use a simple low poly style. No matter what I do, I get this type of effect (blotchy shadows and odd dark lines) Here are my settings Baking a scene already takes around 4 hours, not sure I can increase the resolution any more without Unity crashing during the bake. Am I doing something wrong? Feel like Ive tried everything.


GameObject not destroyed in ExecuteInEditMode and spooky Instantiating I was trying to get familiar with Unity's ExecuteInEditMode Everything is fine it keeps the old object although I have deleted them. And one more thing, although every thing (cube) is instantiated is set as child of GameObject script is attached to, they where the other cubes come from? I have this code using System.Collections using System.Collections.Generic using UnityEngine ExecuteInEditMode public class Road MonoBehaviour public List lt Vector3 gt points new List lt Vector3 gt () public List lt GameObject gt gameObjects new List lt GameObject gt () private int count 0 void Start() void Update() if(count! points.Count) count points.Count foreach(GameObject g in gameObjects) DestroyImmediate(g) gameObjects.Clear() int i 0 foreach (Vector3 point in points) Debug.Log( i " " point) GameObject tem Instantiate(GameObject.CreatePrimitive(PrimitiveType.Cube), point, Quaternion.identity) tem.transform.parent gameObject.transform gameObjects.Add(tem) Here is a snap


Moving a platform left to right with continuous movement I made a 2D game with Unity, and I am trying to create a platform that will move from left to right continuously, but I don't know how to make the platform move a greater distance then 1 to 1 units because I use the Mathf.Sin function. I can only control the speed of the platform. Here is my code private Vector2 startPosition private int speed void Start () startPosition transform.position speed 3 void Update() transform.position new Vector2(startPosition.x Mathf.Sin(Time.time speed), transform.position.y) Here is what the code actually does How can I control the distance that the platform can move to each side? For now, it can only move 1 unit to each side.


Combine Unity games in one app I want to combine multiple Unity games in one Unity app (or other framework if necessary). This app would have a bunch of buttons that will start the desired game. Is this possible and what would be the best way to do this? Thanks!


Foreach list loop problem I am having a problem with a foreach loop. When my AOE ability hits an enemy it creates a CircleCollider2D and puts all the enemies on a list, which then the loop goes through and adds damage to their scripts. private void OnTriggerEnter2D(Collider2D other) if(other.tag "Enemy") targets.Add(other) foreach (Collider2D enemy in targets) EnemyHealth hp enemy.GetComponentInChildren lt EnemyHealth gt () hp.TakeDamage(abilityConfig.baseDamage) print(enemy.name " takes " abilityConfig.baseDamage "damage!") But as you can see from the picture below the loop goes 3 times over one enemy, 2 times over the second one and once over the third. As these enemies are the same type they all have the same EnemyHealth script. If anyone would point me in the right direction I would greatly appreciate it.


is there any method to simply ignore some files in unity build? as im trying to build my new app on unity android specially when i want to use gradle, there is always some conflict with manifest or libraries and ..... for debug and problem exploration i need to ignore some folders to check for those bugs instead of need to move them somewhere else. i just thought about git branching but it can cause lots of branches and maybe not efficient


A pathfinding for dynamic obstacles and player made blockages? Hi I'm creating a TD in Unity 5 and need some help with my Pathfinding. I'm going to use Arons A pathfinding for my AI which enables me to use dynamic objects and update the path during run time. However in my game I want the player to be able to block the minions with special turrets which will force the minions to attack the "block tower" instead to get past to their destination. How could I accomplish something like this? Image for more clarity


How to make changes to array of prefabs in editor to be visible in game window I attached the following script to an empty game object (EnemiesGO) in the editor. public class EnemiesScript System.Serializable public struct EnemyWithType public EnemyScript enemy public EnemyScript.Type enemyType public EnemyWithType enemyPrefabs public EnemyScript enemies void Start () enemies new EnemyScript enemyPrefabs.Length for (int i 0 i lt enemyPrefabs.Length i ) enemies i Instantiate lt EnemyScript gt (enemyPrefabs i .enemy) enemies i .enemyCategory enemyPrefabs i .enemyType When I was populating enemyPrefabs (through the editor) I didn't see the prefabs in the popup selection window so I dragged them directly from the Assets window Assets Resources Prefabs EnemyPrefabs. My question is two fold. If it is possible, how can I get the populated enemyPrefabs array to be displayed in the game window scene window before I run the game? In general, I would like to see changes effected from the editor in the game window before I run the game. How can I access the EnemyPrefabs folder from the popup selection window?


Stencil test doesn't work at all in Unity when I am using a custom shader I am using Unity 2019.3 and I have a custom shader A which contains the code Stencil Ref 5 Comp Equal Pass Keep And the other custom shader B contains the code Stencil Ref 5 Comp Always Pass Replace The stencil test can do the right thing only if I add Fallback "Diffuse" in B, otherwise, it's never working. And A has no code related to Fallback. Since shader A is using for post processing and I did something like buffer.SetGlobalTexture(ShaderID. MainTex,source) buffer.SetRenderTarget(destination) buffer.DrawMesh(mesh,Matrix4x4.identity,material,0,pass) The material uses shader A. Does this cause the issue because before today, I never use the Fallback during stencil test. PS. You can use this and scene named SSS as example. In that scene the shader named Unlit PBR has this issue. If you delete Fallback "Diffuse in that shader, the post processing effect never works.


How to make an object that has no rigidbody2d component smoothly fall on the ground in Unty2d? I have two character in my game enemy and main character. Enemy can throw different objects into the main character. For this moment i am doing this action in such way void FixedUpdate() if (CanMove) transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) public void StartMove(bool canMove) CanMove canMove TargetPlayer GameObject.FindGameObjectWithTag(Tag).transform rigidbody2D.gravityScale 0 This script is attached to the prefab of the object that will be thrown into main character by the enemy. This script is working, but in this case the object that was thrown will follow by main character all the time, because of this line of code transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) To my mind this is not good, because i want to give my player the opportunity to escape from the object that was thrown at him. For example run away. When the object reaches the player position (and the player is on the new position) he will simply fall onto the ground. I did this, but this wasn't looking nice, because when the object was reaching his position, he was hanging in the air. Can anyone give me an advice how to make this process more good looking? Edit I need to make good looking movement of the object, that was thrown by the enemy into main character. Every frame i am moving the instantiated object to the current player position. So the player can't escape from that object, because he always knows current player position. I think that this is not good idea, and i want to give to player an opportunity to run away from that object. In this case i am saving the position of the player into variable, and then every frame i am moving the instantiated object to that position. So when the player run away, the object, that was thrown doesn't know anything about new position of my player. But this is looking not good, because when the object is reaches its destination position he hangs in the air(( Edit 2 I was thinking about destroying that object anyway, but to my mind this will not look good the object is moving and suddenly disappears from screen(. May there is some ways how to make him smoothly fall onto the ground? The problem is in that this instantiated object has no Rigidbody2d component attached to it, so it will never fall down by itself.


Would creating a player scriptable game using Unreal Engine or Unity violate their license agreement? I want to create a game in Unity or UE4 which allows the user to write scripts in Python and run them mainly to control the AI. I will have to find a way to enable runtime script execution first. After searching the internet i was able to find some ways that may work. What i cant find an answer for is how to limit the parts of engine and game code the user has access to so that the player doesnt feel like he's playing it in God mode. And the main question is that even if i am able to restrict access to the API will it violate the terms of agreement for these commercial engines because the player will get access to the underlying engine and will be manipulating objects within it. I don't intend to make a moddable game just a game that requires you to write some code but that would be an extreme case to think about.


Unity 4 Some Rigidbodies Won't Fall Asleep I'm having this problem in the free edition of Unity 4.1 where rigidbodies aren't falling asleep (and yes, I've tried playing with the sleepVelocity and sleepAngularVelocity values!). I've read the docs at http docs.unity3d.com Documentation Components RigidbodySleeping.html but cannot figure out the problem. Here is a screenshot demonstrating my problem Rigidbody Sleep Diagram http uberlethal.com random rigidbody sleeping.png I wrote a script that is attached to the rigidbodies in question, which sets the material color to red if the rigidbody is currently asleep or green if it is awake. The screenshot was taken when all objects were at rest. As you can see, not all of the gameobjects are sleeping. Each piece of debris you see on screen is its own gameobject with a rigidbody and collider. The Unity docs I linked to above state the following Rigidbodies automatically wake up when another rigidbody collides with the sleeping rigidbody when adding forces. Perhaps some clarification on the above might help solve this issue If two rigidbodies are touching when they fall to quot rest quot , will they never stay asleep? Put another way, would they just keep interrupting each other's sleep? As for the quot adding forces quot part, do sleeping rigidbodies awake only when forces are added directly to them, or when any force is added to any object (this is important because I am using a rigidbody character controller which moves via AddForce() calls) I have tried manually sleeping objects myself with undesired results. What usually happens when I do this is that some objects will remain suspended in the air. Let me know if you need other details I have tried a great deal of things.


Changing sprite tint over time in Unity. Sprites affected by "light" Recently I was playing "Altos Adventure" on mobile. I was curious how I could implement an effect similar to their game background. The sprites tint over time to match the time of a day. It's blue in the morning, orange in the evening. Sky color is changing and also mountains tint. I believe it is possible to change solid color sprite and it seems like mountains have only one color individually. Maybe they use other half transparent sprites to change the tint of the entire scene? Like half transparent curtain. But it doesn't explain the smooth transition between colors during the time. Any ideas how I can do the same with Unity and Photoshop? I am also interested in mountain fading effect which appears during rain or snowfall. See the background behaviour lighting effect in more detail in this video Screenshots with different tints of background


How to modularly call a script based on parameters within the script? I am coding an interaction system in Unity that does things based on whether the player taps interaction, or holds interaction. Each object holds their own scripts of how a player can interact with them and what happens (e.g., they can physically lift an object, add an object to their inventory, open close a door, etc) What I want is for the interactable object to call component scripts that have been added to it and categorized as tapInteraction or holdInteraction, but I also want the component scripts to be separated from how they're called (e.g., they might be called via tap or hold, it shouldn't matter). If I use interfaces, the tapInteraction could check for GetComponent lt ITap gt () and the holdInteraction could check for GetComponent lt IHold gt (), but then wouldn't each action need separate scripts defined as Lift ITap and Lift IHold? I feel like there would be a lot of repetition. I'm wondering if there is some better way to go about this. EDIT Thank you very much for the input DMGregory and Alex F! I ended up going with an interface approach similar to what Alex F answered, but with two key differences It was very important to me to have the actions as components on the gameobject since a specific action (e.g. Lift or AddToInventory) would have a large amount of customization from object to object. I also wanted the interaction to return a status as to whether it succeeded or not. As such I created a base class Interaction that implements the interface IInteraction with a bool TryInteraction method, and registers deregisters itself to an interactable object via OnEnable and OnDisable as the tapAction or holdAction depending on if that Interaction is set as a tapAction or holdAction. InteractionLift and InteractionInventoryPickUp inherit that base Interaction class, they implement the TryInteraction interface, and depending on their parameters will register themselves to a interactable object script as either the hold or tap action. Then the interactable object fires the hold or tap TryInteraction accordingly.


Draw line inwards in Unity using Line Renderer Is there a way to draw the line inwards instead of from the center using Line Renderer in Unity? Another option would be to move the Vector points inwards by half the width of the line, but If I have a complex polygon how do I do it uniformly? EDIT Found this https stackoverflow.com questions 1109536 an algorithm for inflating deflating offsetting buffering polygons which may be useful


How can I draw a specific GameObject into a texture in Unity? I need to draw only a few specific objects into a texture (with their material) and then use that RenderTexture as a texture for an another object. I think Graphics.DrawMesh() and Graphics.SetRenderTarget() would be helpful, but I'm not sure. Ultimately I'm trying to create refractive water, which will refract only specified GameObjects, not layers. How can I do this?


Calling Functions from Other Scripts Say I have three different gameObjevcts, each representing rock, paper or scissors. These objects all have a Player script attached to them. The Player script has two functions i want to use, MoveSelected(), MoveNotSeleccted(). When the function CPUMove() is called, I want the program to randomly choose one of the three moves. My question is, how do I call a either of the functions fro another script RPS Game? I thought of using Invoke() somehow but after trying couple of things with it, I got no where. Can someone please help me out? public class RPS Game public void CPUMove() int rand Random.Range(1, 3) if(rand 1) call MoveSelected() for one of the three Player objects and MoveNotSelected() for the other two else if(rand 2) call MoveSelected() for one of the three Player objects and MoveNotSelected() for the other two else if(rand 3) call MoveSelected() for one of the three Player objects and MoveNotSelected() for the other two


Constraining an orthographic camera to an isometric world I am using Unity3D, and I am building an isometric world by rotating a plane on the Y axis by 4.205 units. I am using an orthographic camera. I want to constrain the camera so that the viewport never shows the area outside of the world (in green). How can I calculate the corner points of my rotated plane in screen coordinates, represented by green? How do I stop the camera from scrolling to prevent it from showing the area outside the world, represented by gray?


How to align the Polygon Collider 2D in Unity to match the position of Sprite? How to align the Polygon Collider 2D in Unity to match the position of Sprite? I have a game object. It has a Sprite Renderer with an image. Now I add a Polygon Collider 2D component to the game object, that generates a collider. The shape of the generated collider is correct as expected i.e. it matches the image from the Sprite Renderer. But the position of the collider is wrong. Here you can see what I mean For sure I have a solution I can manually configure the Offset of the Polygon Collider 2D. But that would take a significant amount of efforts and time (because I have a lot of such game objects, which need to have a sprite and collider). So, I am hoping to find a solution which would position the generated collider correctly. I.e. in such a way, so that the boundaries of the collider would match the boundaries of the sprite.


How do I link a GameObject activated state to a UI button being held? How do I go about this functionality When a user taps and still holds onto a UI button, a GameObject will be set active, when they release the UI button, the GameObject will be deactivated.


Material colours in unity not displaying correctly? Even though I've picked blue the color is displayed as something pinkish. All colors are like this


In Unity displaying long lists of information to screen? Tables? Hello folks I'm making a little game for fun in unity, Its a boxing management sim. I've got the code done to create boxers and give them many properties such as names, weights, stats, etc. I've made another screen , lets call it 'office screen' for now. In that I want to open a panel which will show all the boxers in the game (ideally I'd like to be able to make the player be able to filter these results by which company he's signed to etc but I think that might be out of my skill range so maybe i will just make a separate screen for Owned Boxers) But I cannot seem to find a way to display all these infos in a table with columns such as Name Age Company etc I have had a go just using the UI Text components and panels. But thing is, there will be approx 100 boxers or more and this number will always change also. Any ideas for this in Unity specifically? EDIT I am storing all the data just as variables (i think fields) in a class called Boxer which is assigned as a component of a new GameObject i instantiate at the time each boxer is created. So each boxer has its own gameobject. EDIT 2 D i've found this https docs.microsoft.com en us aspnet mvc overview older versions 1 models data displaying a table of database data cs would this be the sort of thing I can add to Unity (assuming I can follow along with the guide)? Thanks for any help


snap an object to another object? so I have some walls which are cubes stretched along a direction.and I have some windows and doors that are suppose to snap to a wall and don't let go until the desired location is out of the snapping range.and in the meantime I want the Objects to move along the wall but never detach from it. if I wasn't clear enough let me know.


Draw wireframe models for Gear VR app in Unity I want to create a 3D Android app for Gear VR that does lets me do the following Read an input file with a bunch of coordinates of points (including information about how they should be connected) Draw a wireframe model with these points Walk around and through the model in first person to look at it from different angles using a gamepad controller. I don't want to directly interact with it! (Maybe have more than one model displayed at the same time, including filled ones) Is it possible to draw 3D wireframe models in Unity using coordinates instead of using already finished models that were created in Blender Maya etc, and if so, how?


Unity ceiling light issues I'm trying to get back into Unity and I've been playing around with lighting. I modelled a simple lightbulb in Maya and have been trying to create a hanging ceiling light but I'm struggling to get it to work. No matter where I place the point light, it appears to originate from the ceiling and the bulb remains dark. Ideally, I would like the light to originate from inside the bulb and spread across most of the room, while also making the bulb glow. I'm sure this is a simple task but I would really appreciate any tips in the right direction. Thanks


Implementing a 4x4 Game Board I struggle with efficiency in code, and I want to start my game off on the right foot. I have a game that I'm making a 4 x 4 map of 'tiles' that a user can build their 'town' on. To keep track of the tiles, I'm planning on simply having a size 16 array of the type of my 'mapTile' enum. EX enum MapTiles defaultTile, homeBase, farm1, farm2 ...and so on... static MapTiles playerMap MapTiles 16 ... default map setup ... Is there a way that is more efficient or more easy to extend way to implement such a map? I'm using Unity and C mostly, though i'm willing to work with any Unity capable language if you have a clever answer.


Different Screen Sizes and Camera in Unity Now I know that no matter what the screen size is the camera will keep its height, so no worries about that. My question is, is there a way to manipulate the camera, either its orthographic size, or its viewport rect width, height, x or y so that the camera will fit perfectly on different screen resolutions. I know this a perfect solution for supporting different screens problem but how do other games do that? I mean I took some games from google play like bunny skater, or stick hero, those games look the same on Huawei P6 which has 1280x720 resoltuion, on Prestigio Multipad 4 which has 1024x768 and on HP Slate 7 which has 1024 x 600 resultion, now my question is how do they do that? I think the closest solution to this is to manipulate viewport rect of the camera, I'm saying this because I found a script that does so but it leaves black bars on top and bottom, the game looks the same on every device though but as I said it leaves black bars on top and bottom, so is there a solution on how to do this?


Scene building for procedurally generated tile based world in Unity i'm making a procedurally generated side scrolling and destructible tile based world. So far I've got the values generator (for deciding which tile to place where) a testing scene generating one object per tile (a mesh with 2d box collider, inactive at start) map chunking (separating the map into chunks to show only what is visible) visibility based on orthographic camera size (it's not much but the camera can zoom in or out) the chunks are 32x32 tiles in size the maximum chunks I've seen is around 25 This works fine for testing the world generation, however there is massive stuttering when moving around with camera zoomed out to the maximum. It's less when zoomed in, but it is still noticeable. From testing, I've found out that its obviously the building in the scene that causes the major part of the stuttering. I've been searching for better ways of building the scene but there are a few constraints that make most of the non viable The world is destroyable, so I need to be able to interact with each tile There are textures coming on top of the tile texture depending on context (selection rectangle, decoration, glow...) The tile texture itself is not a single sprite but a repeatable texture, so it needs to be places based on coordinates so it properly repeats itself. So far I've looked at TileMaps Mesh melding Texture bombing None of these seem to be able to fulfill the constraints fully. Is there a way to fulfill the constraints while improving scene building or am I missing something? Please help.


Additive Scene Loading Buttons not Becoming 'Active' I'm quite new to Unity but I'm making a game, and have created a simple Pause menu, when a key is pressed (escape), I just load a Pause scene, additively, and set that Pause scene to the active scene, however, only the buttons on the previous 'game' scene are interactive. The mouseEnter, exit etc aren't triggering on the pause menu buttons, despite the pause menu being overlayed on top of the 'game' scene the Pause scene being the active one and the 'game' scene buttons are still the interactive ones (i.e. register clicks, mouse overs etc). Obviously when I open the pause menu, I want the pause menu buttons to be the interactive ones (registering clicks, mouse over etc), not the previous 'game' scene buttons. The pause menu scene interacts perfectly when loaded additively with a scene that had no buttons. Many thanks.


Why use convex polygons and not concave ones in path finding? I read in Unity's path finding documentation that they use convex polygons because there won't be any 'obstruction' between 2 points. Then they add their vertices as nodes along with starting and ending points and traverse them using A algorithm to reach the required destination. However, I do not understand what they mean by quot no obstruction between 2 points quot . I tried to check the differences between concave and convex polygons but only the angle differences come up (in convex the interior angles must be less than 180 degrees)


Facilitator UI on desktop screen for VR Hey and thanks in advance for any help pointers The solution is probably straight forward but i am still a little inexperienced (while creating quite a few different VR unity projects mostly study related, i never really build anything so the editor allowed for some shortcuts. see below). I am currently developing for Windows mixed reality with unity. I am struggling to figure out how to make a (possibly secondary) application window run on the desktop that can be used during facilitated VR experiences to change settings and generally provide facilitator input to the application while the participant would just perceive the VR world. Edit I have a similar project that is developed with Steam vr library Open VR that works exactly as expected and portrayed by the unity editor i.e. the desktop will shows the ingame footage the screenspace overlay UI (which is interactable).Nevertheless quite a few features where implemented with the MixedRealityToolkit so I'd prefer to stick with that. And was wondering if there is a way to achieve the same similar behavior with it. Now with MRTK everything works straight forward when running from unity editor just making a canvas screenspace will prevent it from showing in vr while it can still be interacted with. the problem is that the facilitators themselves are a third party and having a build would just make their handling of the solution much easier. Not to mention performance gains from building and cleaning the project(?). it will probably come down to creating a secondary window that runs on the desktop since my understanding is that uwp with MRTK just runs in the wmr portal rather than a separate app and that the WMR portal simply copies the Headset render to the desktop. But i am completely blank on how to achieve this and was hoping that someone might have struggled with this before. But i couldn't really find anything. I'd prefer not to have to resolve to Networking, and will attempt to convert to Steam VR OpenVR in the meantime..


Make an arrow to point at a direction from UI I want to have a guiding arrow on the left side of UI. The arrow is child of the player's camera and it's rendered from another camera into render texture. The render texture is displayed on the screen. The arrow is rotated via transform.LookAt(targetPosition) The problem I'm having is that although it does point in the right direction, form player's point of view it looks like the arrow is pointing somewhere else. I want that arrow to point from the point where it's placed on the UI. It should look something like this I tried to do this Vector3 direction targetPosition arrowRawImage.rectTransform.position transform.LookAt(direction) but it didn't work.


Multiplayer turn based Android iOS We're developing a mobile endless runner game, on Unity3d where you can challenge your Facebook friends. The only interaction between the players is the challenge one player challenges the other, then each player plays when he wants, and after both players finish (when their character dies), their scores are compared to determine the winner. What system would you recommend that would allow us to implement this functionality, considering scalability, cost and ease of use? Thanks in advance!


My Canvas has an image which I am using for my background but it is blocking my Camera from seeing my Game Scene So I am not entirely sure how to explain this as I have not had any luck searching online and I'm sure this is a simple problem but I'm being stupid and can't see it. I have a Canvas which is for my UI obviously and I have added an Image as a Background to the Canvas. The problem I am having is that due to the Image on the Canvas it is blocking my Camera from seeing the Scene with my game object you can see in the background. On the Canvas, I have tried playing around with Sort Order, Render Mode, and see if I could edit the Z Position but I can't seem to do that. I'm not too sure what I have missed but I must have missed something. Any assistance would be great.


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


Play a sound on button click before loading the load scene in Unity3D I am trying to play the sound of the button click before loading the scene in unity. However, the sound is never played. Below is my code, help would be appreciated. public void RestartGame() audioManager.PlaySound(forwardSound) StartCoroutine(DelaySceneLoad("Gameplay")) IEnumerator DelaySceneLoad(string scene) yield return new WaitForSeconds(forwardSound.length) GameTracker.SetGameOver(false) SceneManager.LoadScene(scene)


How can I add up the Transform GameObjects in the Array of Waypoints in Unity? I come up with this code and I try to get the waypoint 1 when I reach the waypoint and it adds up till the last waypoint. I get Array is out of Index error. I guess I need and foreach loop of waypoints ? Code public float speed public float turnSpeed public Transform waypoints private int currentWp 0 void FixedUpdate () if(waypoints.Length gt currentWp) return player.position Vector3.MoveTowards(player.position, waypoints currentWp .transform.position, speed Time.deltaTime) var rotation Quaternion.LookRotation(waypoints currentWp .transform.position player.position) player.rotation Quaternion.Slerp (player.rotation, rotation, turnSpeed Time.deltaTime) float distance Vector3.Distance(player.position, waypoints currentWp .position) if(distance lt 10) currentWp


How does Unity Static batch handle submeshes I have the following 2 meshes Mesh 1 Submesh 1 Mat 1 Submesh 2 Mat 2 Mesh 2 Submesh 3 Mat 1 (same as mat1 from submesh 1) Since submesh 1 and 3 have the same material and they are all static, I'd like to render submesh 1 and 3 in a single drawcall. However, Unity is failing to batch those submeshes together. Is there a way to achieve 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)


Using UDP vs Websockets I am running a Unity Game on a PC (for development purposes) and then on an Android phone (for production). I need to send data to the Game continuously from a WiFi enabled microcontroller (Esp32). Is it better for me to use UDP or Websockets for data transfer? What are the pros and cons of each method? In this scenario, the game device will act as a mobile hotspot while the esp32 will connect to this hotspot.


Exporting WebGL For Mobile Browsers I was asked by a client to create a pretty simple 3D game that will be embedded on a website, a plain landing page that will contain the game and will be played on mobile devices. The game itself has no complexity whatsoever, not in the functional aspect and not in the lighting shaders aspect the basic functionality is a simple finger swipe in order to quot throw quot a ball. I have checked and concluded that opening a webGL game on mobile devices might cause issues and only high end devices can run the game smoothly. My question is Is there a go to solution or any solution in which I can develop the game on Unity and build it for webGL in a way that it will be compatible with mobile devices? Or my only option is to develop the game using plain JS?


Process for converting unity asset to scenekit scene resource Has anyone successfully figured out a method for converting a unity3d asset to a 3d SceneKit model scene? I imagine it would require exporting the asset into some third party file type, and then importing into scene kit. If you have any knowledge that can help me, would you kindly explain the process? Unity3d has a fantastic asset store, and I want to import some of these things to a project that requires scenekit (unfortunately, "just use unity" is not really an answer to my problem set).


Unity3D CrossPlatformInput StandardAsset Multitouch I have a small game I am working on, and I am trying to add touch support to it. Before I try to add that into the real game I wanted to do a test run on a small project. The project consists of a capsule to be the player, and the application accepts movement from a on screen joystick, and accepts a button click from a UI button. The button triggers the attack, and the joystick triggers the movement. Both of these controls work as designed but they will not work together, meaning I can do one or the other. I was hoping to use the standard asset as to not re invent the wheel for speed... below is the code that "Should" be triggering when both controls are used, just as a note this same code works when I use mouse and keyboard together so this is something to do with the mobile stuff.. using UnityEngine using System.Collections using UnityStandardAssets.CrossPlatformInput public class PlayerController MonoBehaviour public float playerSpeed 10f Transform weapon Use this for initialization void Start () weapon transform.FindChild("Weapon") Update is called once per frame void Update () DirectionalMovements() ButtonPresses() void ButtonPresses() if (CrossPlatformInputManager.GetButtonDown("Fire1")) weapon.GetComponent lt Sword gt ().AttackOne() void DirectionalMovements() float moveVertical CrossPlatformInputManager.GetAxis("Vertical") playerSpeed Time.deltaTime float moveHorizontal CrossPlatformInputManager.GetAxis("Horizontal") playerSpeed Time.deltaTime Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) transform.Translate(movement, Space.World) if (movement ! Vector3.zero) transform.rotation Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement.normalized), playerSpeed) Any thoughts would be greatly appreciated.. I just do not see why both controls are not picked up here.


Where's Anti Aliasing in LWRP? In Unity 2019.2 LWRP (lightweight render pipeline project) the default Game Output(Quality High) is rendering with jaggies. Inorder to get a clear render ,while looking for the Anti Aliasing option it doesn't seem to be under the default location (Edit Project settings Quality )for LWRP projects. Where is the Anti Aliasing option in LWRP and is there any other way to get a clear game render?


Get the object that triggered the event I am trying to make a simple tooltip for my game. I added event trigger to object that I want to trigger an event on mouse hover (PointerEnter). And I want to get the game object that triggered the event in ShowTooltip(). I tried requiring BaseEventData in the void but it gave me error. void ShowTooltip(BaseEventData baseEvent) Debug.Log(baseEvent.selectedObject.name) The error Failed to call function ShowTooltip of class UIManager Calling function ShowTooltip with no parameters but the function requires 1.


How to change a variable in the spawnpoint from another prefab I refer the website for proper way of referencing the script How to call a public function from another script in Unity? but it does not work, still return a nullreference exception in the example below. Not sure how to fix it.Apart from that I also consider using int a public int A get set and in HPscript using spawnpoint.A spawnpoint.A 1 but it come out the content is for read only. Below is the codes I using. I attach this code to a capsule gameobject that is use to spawn prefab gameobject,drag and drop prefab to the enemy GameObject inspector window, this part working correctly. using System using UnityEngine public class Spawnpoint MonoBehaviour public GameObject Enemy public int a int currentstate 0 int previousstate 0 void Counting() the below if statement is to ensure the Gameobject only spawn once when condition become true in every 10seconds var d DateTime.Now.Second 10 if(d 0) currentstate 1 else currentstate 0 void Spawn() Stop spawning when Gameobject equal 5 if (d 0 amp amp currentstate! previousstate) if(a lt 5) Instantiate(Enemy, new Vector3(UnityEngine.Random.Range(0, 4), 1, UnityEngine.Random.Range(0, 4)),Quaternion.identity) a a 1 void Update() Counting() Spawn() previousstate currentstate The script below is not working. I want the HPscript to deduct the value quot a quot ,in Spawnpoint script so the script will continue spawn enemy when number less than 5.This script is attached to the prefab gameobject that is place in asset folder. using System using UnityEngine public class HPScript MonoBehaviour Spawnpoint spawnpoint void Start() spawnpoint GetComponent lt Spawnpoint gt () public void counting() var c DateTime.Now.Second 30 if(c 0) spawnpoint.a spawnpoint.a 1 Destroy(gameObject) void Update() counting()


How I can count how many time gameOver scene is loaded? I'm building a game using unity 3d and I want to add an interstitial ads to it, but I want it to appear after the player lost every 3 times. So when the player loses for the first time the ads will appear, and when he loses for the second and third time, nothing appears until he lost for fourth time.


Unity Ragdoll Colliders don't collide I have a humanoid character with Ragdoll setup in Unity. However the box capsule colliders on the various parts of the body don't collide with other static geometry. They do collide with the ground but not with any other static meshes. Is it possible to use them as colliders towards static meshes and what do I need to do for it to work?


What is the best way to increase slowly object movement speed and slow down the object near the end? There a Lerp but also SmoothDamp. In this script I'm using SmoothDamp but why not using Lerp ? And how should I use this script with the SmoothDamp tp make slowly increasing speed at the start ? Now it's only slow down at the end but I want it also to increase slowly at the start and then slowly down near the end. using System.Collections using System.Collections.Generic using UnityEngine public class MovementSpeedController MonoBehaviour public Transform target private Vector3 velocity Vector3.zero public float smoothTime 0.3F void Update() transform.position Vector3.SmoothDamp(transform.position, target.position, ref velocity, smoothTime)


Blender FBX exports to Unity3D have incomplete animation sequences Using Blender, I have rigged and animated this model with this attack action. I exported this model to an FBX format and imported the said FBX file into my Unity3D project. However, when I imported it, I noticed that the animation sequence is incomplete As you can see, the sword does not animate correctly and remains unmoved in its original position. In Blender, the sword and scabbard are animated in Pose mode with IK and other constraints. However, as I understand it, FBX bakes these constraints into the animation, so I'm not sure if that causes the issue. Why is the sword not animating correctly? How do I fix this so that the Unity animation is 100 faithful to the Blender animation?


Run some objc code very early in unity iOS game lifetime I want to hook up a crash reporting service to my unity iOS game. It's just one line of objC to add, as early into the app lifecycle as possible, but I'm not sure how to get it to run. I know I could make a native plugin and then call that from some Awake() function in C , but that's too late for my purposes. I'm not a native iOS developer, but I know enough to be dangerous. I have been able to google enough that I know I want something to with UnityAppController, probably preStartUnity(). But that's all. Has anyone got further resources on how to do this? Or another way, if I'm barking up the wrong tree? edit I'm on unity 4.6.


Why do not Easy Mobile Pro scripts know about each other? I am getting this error when I try to build the project Assets EasyMobile Scripts Modules NativeAPIs NativeUI Nati veUI AlertPopup.cs(68,17) error CS0103 The name 'AndroidNativeAlert' does not exist in the current context I tried adding this to my NativeUI AlertPopup.cs if UNITY ANDROID using EasyMobile.Internal.StoreReview.Android endif Hint says unnecessary using. Googling, searching Unity EMP forum and thread did not bring any results. Unity version 2019.2 .net 4.x EMP 2.5 If I try adding a breakpoint it says The breakpoint will not currently be hit. Unable to find a corresponding location. AndroidNativeAlert is a static class, have have no clue why it can't been seen from the other one.


How can I set only the players X rotation to 0 in Quaternion.Slerp in Unity? I want to set the players X axis to zero while he is turning to the target Object but I dont get it to work. Code public float rotationSpeed void OnMouseDown() PLAYER ROTATION TO ORE OBJECT var rotation Quaternion.LookRotation(transform.position player.transform.position) player.transform.rotation Quaternion.Slerp (player.transform.rotation, rotation, rotationSpeed Time.deltaTime)


How do I get a Light's Range value in Shader? I'm trying to write a simple frag vert shader that, depending on whether it is in the range of a light, will paint the appropriate colour from either the 'lit' texture or from the 'unlit' texture. Therefore, I need to compare the distance between the light to the range of the light. I've been googling all kinds of things, but I can't seem to find a way of accessing the range value of the light. Is there a way to do so? If not, is there some kind of derived data I could use as an alternative? I was able to find this method here, which seems to be the most promising so far, however after playing around for a bit, I still can't seem to get what I need. There's some talk about LightMatrix0 not being populated. Can anyone confirm? I've also had it suggested to use SetFloat() and pass in the range like that...however, that provides no easy way of telling one light apart from another short of using the light's position as a key. As several key lights in the game will be moving this is just ugly and inefficient. Update I found the variable unity LightAtten in the Unity Shader Variables documentation. However, this is only used for Vertex Lit shading, which isn't exactly ideal, especially considering the lack of console support. Could there be a way to pipe this variable to Forward Rendering? Update 2 For clarification, shading should otherwise be 'flat' (ie no need for diffuse etc) Also, what I've currently got (albeit, not currently working as desired and currently using a workaround) Shader "Lantern Flat Pullup" Properties LitTex ("Lit (RGB)", 2D) "white" UnlitTex ("Unlit (RGB)", 2D) "white" Falloff ("Falloff", 2D) "white" Pullup ("Pull up Point", Range(0,1)) 0.7 SubShader Pass Tags "LightMode" "ForwardBase" LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform sampler2D UnlitTex uniform float4 UnlitTex ST uniform sampler2D LitTex uniform float4 LitTex ST uniform float Pullup uniform float4 LightColor0 struct VI float4 vertex POSITION float4 tex TEXCOORD0 struct V2F float4 pos SV POSITION float4 tex TEXCOORD0 float4 posWorld TEXCOORD1 V2F vert(VI v) V2F o o.pos mul(UNITY MATRIX MVP, v.vertex) o.tex v.tex o.posWorld mul( Object2World, v.vertex) return o float4 frag(V2F i) COLOR float3 flatReflection LightColor0.xyz (1 length( WorldSpaceLightPos0.xyz i.posWorld.xyz)) float4 color Improve for light color etc if(length(flatReflection) gt Pullup) color tex2D( LitTex, i.tex.xy LitTex ST.xy LitTex ST.zw) else color tex2D( UnlitTex, i.tex.xy UnlitTex ST.xy UnlitTex ST.zw) return color ENDCG FallBack "Diffuse"


How to share image in persistentDataPath to facebook feed? I'm trying to share an image taking from CaptureScreenshot() using FB.ShareLink(...) to Facebook. My code is the following (After calling FB.Init(), etc..) string tmpScreenshotPathname "file " currentScreenshotPathname System.Uri contentUri new System.UriBuilder(tmpScreenshotPathname).Uri System.Uri imageUri new System.UriBuilder(tmpScreenshotPathname).Uri FB.ShareLink(contentUri, "Test", "Test desc", imageUri) However, when open the FB share, the page opens for a split second before returning me back to the game. I tried using a normal Uri such as http ........jpg and it works fine, but when I try to use a local Uri, it fails. Is there any way to share the image to the feed without uploading it to the user's Facebook gallery using FB.API? Because there's the case where the user might decide not to share the image to the feed.. but it would have already been uploaded to his gallery from FB.API.


Unity crashes when opening a project Why does this happen? I'm new to Unity development. I have installed Unity yesterday (2015 09 06). This is the error that I get


How to perform some custom math between the model matrix and the projection matrix? I'm trying to write a shader in Unity that will perform some custom math after the model view matrix is applied but before the projection matrix is applied. First off, I'm not sure whether I should be using a surface shader or an unlit shader. My impression is that a surface shader can do everything I need it to and the outcome will look better with less effort, is that right? I'm thinking that what I can do is manually apply the model and view matrices in the vertex shader, and then I have to tell it somehow to only apply the projection matrix in the rasterization step. Any idea how to go about this, or a different way to achieve the same result?


How to avoid assigning the same GameObject individually for every prefab? In many times, prefabs that share the same script may require the same GameObject in the script. For example, in my game I want to make a series of card prefabs. Each card has their own image when shown, but has the same back image when hidden. My script for card is public class DraggingCard DragAndDropItem public Sprite secretSprite This is the same for every card Sprite oringinalSprite This is individual for every card Image image public void Awake() image GetComponent lt Image gt () oringinalSprite image.sprite public void Activate() image.sprite oringinalSprite public void Hide() image.sprite secretSprite But if I write this, I'll have to assign the secretSprite in the inspector for every DraggingCard prefab. I tried to set secretPrefab to be static or const but neither worked. I believe there must be a clever way to avoid the repeat work. Could anyone tell me that? Thank you!


UnityWebRequest security I have a game where I would like to register users and post the outcome of matches between two users through web requests in Unity but have some security questions regarding UnityWebRequest. Assume the following code for sending a web request public class TestHTTP MonoBehaviour SerializeField private bool sendRequest false Update is called once per frame void Update() if (sendRequest) Model testModel new Model() testModel.ID quot 0001 quot testModel.name quot Random Name quot testModel.int1 555 StartCoroutine(SendWebRequest(testModel)) sendRequest false public IEnumerator SendWebRequest(Model m) string json JsonUtility.ToJson(m) string text JsonUtility.ToJson(SimpleAESEncryption.Encrypt(json, quot some password quot )) using (UnityWebRequest request UnityWebRequest.Post( quot some https quot , json)) request.method UnityWebRequest.kHttpVerbPOST request.SetRequestHeader( quot Content Type quot , quot application json quot ) yield return request.SendWebRequest() if (request.isNetworkError) Debug.Log( quot NETWORK ERROR quot request.error) else if (request.isHttpError) Debug.Log( quot HTTP ERROR quot request.error) else string returnData request.downloadHandler.text After doing a bit of testing I noted that sending via http would give a plain text body, which was remedied by switching to a https target. Is this enough of a level of encryption or should I add a layer of encryption for the model prior to sending? Lets assume my model contains data regarding the outcome of a match between two players. Would https (TLS 1.2) be enough to stop someone resending the same request packet to inflate their number of wins for example? Or should additional measures be taken to stop this?


Why doesn't my material show up on my imported model (Unity Blender) UPDATE The material does work on smaller objects like a simple sphere, but not on my big arena model, which is actually imported from blender, any suggestions? UPDATE Tried to export as .fbx, but doesn't change anything. I've imported this material pack https www.assetstore.unity3d.com en ! content 13004 I tried to apply it to my mesh, but only weird things happen, I can't see the texture at all. So I tried to apply this material in the "shader calibration scene" and that worked without any problem, even updating to the standard shader worked fine. So I tried to fix it with the following things Rebaking lighting Restarting Unity Tweaking the material settings Tweaking quality settings in Unity Building the project All these things couldn't fix it, but it should most likely be related to my project settings, since this material is working in another project (shader calibration) Here are my quality settings I'm not sure, which information is needed to answer the question, but I can provide it if you ask for it. Update with Object properties


Replacing all objects in scene with another object I have around 100 objects (prefab A) in my scene, all in different positions. Is it possible to replace all of these objects with another object (prefab B), so that the prefab B objects are placed in the same position as the prefab A objects were? I want this done in the editor, not in game.