_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Code Logic's execution with respect to time Events I have to show complete 24 hours cycle in Unity3d Scene. Where different kind of task will be executed in different Times. Suppose at 2pm I have to move a car, at 6pm An Aeroplane will land on airport at 07 07pm I have to open the door of Market's Buildings and so on different task works execution at different timing. Now, I have some basic animation e.g., car, Aeroplane and door etc.,. Now I am confuse that how to play and stop my animation according to the time. And time can also be changed manually using GUI. If currently 6pm (animation working) then user can switch to 8am to view 8am time's animation (or code execution). And User can also fast the timing to view complete hours in a single minutes or in an hour. I can use if else in Update Events but I guess this is not the right way to do and will be very difficult if I require to show significant number of works in different time duration (which means significant number of if else statements). Just like below void Update() if(time 1) logic if(time 2) logic if(time 3) logic ... so on, tedious way ... and also not possible if time require between the hours, suppose 06 06pm What to do ? How to handle this? |
0 | Why does the script stop working after respawning? I have a flying enemy that follows the player public class MoveTowardsPlayer MonoBehaviour public float moveSpeed, sightDistance public Rigidbody2D theRB public Transform target private void Start() theRB GetComponent lt Rigidbody2D gt () private void Update() Vector3 targetDir target.position transform.position targetDir targetDir.normalized float dist Vector3.Distance(target.position, transform.position) if (dist lt sightDistance) theRB.velocity targetDir moveSpeed And here is what happens when the enemy dies, and then respawns public void Die() Instantiate(enemyDieEffect, transform.position, transform.rotation) gameObject.SetActive(false) public void Respawn() gameObject.transform.position initialPosition gameObject.SetActive(true) currentHealth maxHealth The enemy respawns if the player dies and goes back to the last checkpoint. Interestingly, if the player dies before reaching any checkpoint, the MoveTowardsPlayer scripts still works after respawning. It only stops working after any of the checkpoints are reached. For the sake of completeness, here is the Checkpoint script, which has absolutely nothing to do with the enemies public class Checkpoint MonoBehaviour private Animator animator public bool isReached Start is called before the first frame update void Start() isReached false animator GetComponent lt Animator gt () private void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Player quot )) CheckpointController.instance.DeactivateCheckpoints() animator.SetBool( quot isActive quot , true) CheckpointController.instance.SetSpawnPoint(transform.position) public void ResetCheckpoint() animator.SetBool( quot isActive quot , false) |
0 | How to sample from six cubemap images for a skybox in Shader Graph? I'm trying to update a skybox shader to URP and reimplement it in Shader Graph. The shader code itself is pretty straightforward, but I don't know enough about Shader Graph yet to set up the basic skybox. It's a standard cubemap skybox made up of six textures for x, x, y, y, z, and z. Trying to Google different variants of "unity shader graph cubemap skybox" turns up tons of noise and nothing actually useful that I can see. Does anyone know what the basic node setup is I would need to input six images and output a skybox? |
0 | 2D 3D Soft body physics in Unity I want to implement soft bodies in my game similar to this link. I tried using this Soft body simulation plugin but it has the following problems Only works with box colliders. Doesn t work with Unity s physics engine i.e. the bodies don t react to the forces applied. For my game, The soft bodies should be able to collide and interact with any types of colliders (including mesh collider). The bodies should work with Unity s physics engine i.e. the bodies should react to the forces and gravity applied. I am flexible in implementing soft bodies in 2D or 3D. I would appreciate any suggestions and thoughts on this topic. |
0 | Best way to create a Chromadepth shader for unity? I'm trying to create a chromadepth environment in unity3D. So the camera sees close objects colored as red, and then farthest objects as blue. And everything in between falls down the color spectrum (Red orange yellow green blue) I've looked into a few things such as z depth or even using fog for this kind of thing. But I'm not sure what the best way to approach this is or maybe it's already been done before but I couldn't find it in the asset store. I Thanks in advance for your thoughts and time, it is much appreciated. |
0 | How to import character package in Unity I recently made a game in Unity 3D and I tried to import the FPS Controller package as the tutorial I was following said, but when I clicked Assets Import Package the only thing I saw was a button saying 'Custom Package' How do I get the character option when I click 'Import Package'? |
0 | Unable to save player data in a binary file within Update() method I'm trying to save player life within a binary file in Application.persistenceDataPath. I've written a method to store the player life public void SaveLife() BinaryFormatter bf new BinaryFormatter () FileStream file File.Open (Application.persistentDataPath " playerInfo.dat", FileMode.Open) PlayerData data new PlayerData () data.savedLife life bf.Serialize (file, data) file.Close () The problem is that when the SaveLife() is called OnApplicationQuit it works. Instead, if I call it within an Update() method of a class, it doesn't work. The Update() method is called when a certain event is triggered void Update() if (life lt 20) if ( certain event is triggered) SaveLife() lifeTimer Time.deltaTime if (lifeTimer lt 0) ResetLife () The container class for the data is Serializable class PlayerData public int savedLife What could be the problem? |
0 | is there a way to alternate between two state machines? I'm programming an enemy on Unity that has two state machines, one controlling the quot normal quot behaviour of the enemy (that consists in three states idle, patrol and chase) and another one controlling the battle behaviour of the enemy (that consists in three more states attack, dodge and run away). I'm doing these state machines by using enums, like the following code public enum StateMachines NORMAL, BATTLE public enum NormalStates IDLE, PATROL, CHASE public enum BattleStates ATTACK, DODGE, RUNAWAY I want to loop between the Normal and Battle state machines but I have one problem that is they always get executed at the same time. Is there a way I can alternate between state machines through code in a single script (by conditions)? Thank you! |
0 | NavMesh Changing Mesh by Jumping upwards I have been playing around with the NavMesh and I have seen that there are different situations where an agent has to change meshes. When it works Everything seems to work alright with links, if I try to make the agent jump from a mesh to another one, tweaking the "Jump distance" paramenter Another scenario is when the agent needs to fall to another mesh to reach the target. This one also works, when I tweak the "Drop height" parameter. When it does NOT work But there are 2 different scenarios, where the agent cant reach the target. The first one is when the agent must jump upwards instead of dropping. And the other scenario is when the agent needs to fall to another mesh that is not directly below the one he is standing on. How could I do so that the agent jumps either to move upwards, or to land in a lower mesh? |
0 | How to stop car from slipping backwards on a slope? I am trying to simulate a car in Unity, the slope of the road is high so the car slips backwards. Is there any physics property which can stop this from happening? Thanks in advance. |
0 | Simple Line Formation I'm working on the first formation for my game's troops. These should simply stand on land, facing the same direction. To achieve this, I tried to create offsets towards a pivot unit, that is approximately the unit in the center of the formation. The units are (temporary) elements of a squad list withing the Squad class. I divide the List by 2 and get the closest integer, that should be the pivot point of the formation. Now I generate offsets for all units on the left side (Unit 1 to pivot 1) and right (pivot 1 to last unit) based on the distance gaps. This is the code for the line formation. Sadly, the units are only forming a very stange line with no visually detectable system int count (int)(squadMembers.Count 2) pivot squadMembers count center pivot.transform.position switch (type) case FormationType.Line int space 5 for (int i 0 i lt squadMembers.Count i ) Unit tmp squadMembers i int dist 0 if (i gt count) dist (count 1) space center.x dist if (i lt count) dist (count 1) space center.x dist tmp.StartMove(center) break It also appears that this only works along the x axis, any idea how i can realize this with the walking facing direction ov the pivot? Is there any (obvious) error? How can I improve this script? PS Any idea, how I can transform this into a double line (2 Lines behind with half spacing) |
0 | How do I fix "Invalid character '' in input string at LitJson.Lexer.NextToken ()" when trying to use JSON from URL? When trying to use a Json file served by a url I am getting the error JsonException Invalid character '' in input string it happens when I use this method IEnumerator GetText() UnityWebRequest webjson UnityWebRequest.Get("http awebsite.com Art .json") yield return webjson.SendWebRequest() if (webjson.isNetworkError webjson.isHttpError) Debug.Log(webjson.error) else The following line is giving me the error ItemDatabase lt GetText gt d 3.MoveNext () (at Assets Version2.0 Scripts ItemDatabase .cs 38) itemData JsonMapper.ToObject(webjson.downloadHandler.text) Debug.Log(itemData) ConstructItemDatabase() I have tried to use Trim() itemData JsonMapper.ToObject(webjson.downloadHandler.text.Trim()) But still have the same result. I have tried what is suggested in this question answer, but it seems to not fix the issue I have. |
0 | Can I reset the DisallowMultipleComponent attribute in child classes in Unity somehow? Can I reset the DisallowMultipleComponent attribute in child classes in Unity somehow? I want to create my base class DisallowMultipleComponent public class MyCompanyClass Monobehaviour I want all my component scripts to inherit from the MyCompanyClass. So, I will be able to add only one instance of my component script to a game object at a time. I need it for most of my classes. But for some classes I still want to preserve the ability to add a few class instances to a game object, while still inheriting from the MyCompanyClass (because I am going to put some custom behavior into it, which is going to be used by all my component scripts). So, I was trying to search for something like AllowMultipleComponent , but found nothing. Is there maybe another way to achieve what I want? |
0 | How to use sprite as font in Unity? I've started working on my first game in Unity It's very simple, there's a spinning block in the middle, and there are spinning blocks coming from all sides. When they hit the middle block, you lose a life. You have 3 lives. I've hit a bit of a brick wall, here, though I can't seem to find anywhere how to use a sprite atlas as a font, or at least be able to sprite my own font. Does anyone know how to do this? |
0 | How can I combine sprites and attach them to a GameObject? I have the following sprites Background Foreground Combined they should look like this The first problem is Unity can only show one sprite with its Sprite Renderer, so I can't combine them with it. The second problem is the bomb sprite should not be rotating along with the background, like so How can I do this? |
0 | How to replicate Unity's Rigidbody.AddForceAtPosition in C ? I am trying to replicate the function Rigidbody.AddForceAtPosition of Unity in C , it means, to apply force to a body offset from its center. How could I achieve that in C ? |
0 | How to construct a propeller clock in Unity? I am considering the possibility of using Unity to construct a propeller clock https www.youtube.com watch?v 6JnAxTXApw . It's an array of LEDs on a PCB board connected to motor that spins at a high RPM. The LEDS flash on and off such that it generates the appearance of a clock face. So far, I've tried turning a red pointer in a circular path with high RPM in Unity, but I don't get an image of a circular red disc. Instead I see a pointer showing random discrete movement in a circular path. Is there any suggestion to rectify this issue? |
0 | Reloading scene in Unity gives weird result I am making an infinite racing game where you fly an airplane while trying to avoid obstacles. I recently finished my menu that comes up when you die. When I press the restart button that simply reloads the current scene like this SceneManager.LoadScene(1) it gives me a weird result. The obstacles starts generating at about the same position as you died previously. I never get this problem when I start the game with the Unity play button. The only thing I could think off was player prefs. It should not affect the generation of obstacles but tried anyway to use PlayerPrefs.DeleteAll() before reloading the scene, but that did not work. What could be causing this strange problem? |
0 | How to make a 2D neon like trail effect in Unity Recently I've been toying around with neon ish effects for a game I'm making and wanted to share my results with you. If you guys have any other methods of achieving this result, please be sure to share. |
0 | Additive scene loading to UNet I have a main scene where my player is loading as I start or join the server. On some player action, I want to load additive scenes in to my main scene. It is loading fine on the client, but not across the network. My other clients are unable to watch it. I checked different links, and found a forum post and a Unity Suggestions page. It seems, to me, that this "Additive scene loading to UNet" feature is not available in Unity. If additive scene loading in UNet is not available, then what are the alternatives? I am able to load scene through ClientRpc . Is this the correct way to do this? ClientRpc public void RpcLoadLevelAcrossNetwork() SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive) |
0 | Which GameObject should I put the animator on? I have a GameObject. One of its children is an empty GameObject, whose children are the body parts which need to be animated. Character (root) gt Body gt gt Body Parts Should I put the animator on the root GameObject ("Character")? Or on the empty child ("Body")? Does it matter? What benefits would one way offer over the other? Or is there another approach I should be taking? This is for 2D sprites animations. I am trying to figure this out before making all of the animations to avoid redoing them. |
0 | Move an object with other objects connected (via joints) the right way What is the best way to move an object with other objects connected to it via joints? Let's assume we have the following setup A player that can move on the x and the z axis "Normally configured" RigidBody Moving like this void FixedUpdate() Vector3 movement new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")) movement movement.normalized 2f Time.deltaTime m rb is the RigidBody of the player m rb.MovePosition(transform.position movement) Another object that should be moving with the player as it were its child Connected to the player via a fixed joint "Normally configured" RigidBody When moving the player without any object connected the movement looks as expected Now moving the player with the object connected results in some kind of dragging effect as seen here One way to solve this behaviour would be to also move the connected object m otherRb is the RigidBody of the connected object (m other) m otherRb.MovePosition(m other.transform.position movement) Is there a better way to solve this? Shouldn't the joint handle the movement of the other object? Moving the connected object like this results in many problems like to high impulse forces when colliding with something as both elements get pushed towards the collider. Also handling the rotation of the connected object isn't as easy as the position. |
0 | How to Replace two object by rotating in center I created Find Rock game but I have problem In replacing two object by rotating in center and when rotating finish stop rotating how can I do this? using UnityEngine using System.Collections public class example MonoBehaviour public GameObject obj public int Randomize new int 2 void Start() StartCoroutine (Delay ()) IEnumerator Delay() Randomize 0 Random.Range (0, obj.Length) Randomize 1 Random.Range (0, obj.Length) while (Randomize 0 Randomize 1 ) Randomize 0 Random.Range (0, obj.Length) yield return new WaitForSeconds (2) obj Randomize 0 .transform.rotation Quaternion.Euler (new Vector3 (0, 0, 0)) obj Randomize 1 .transform.rotation Quaternion.Euler (new Vector3 (0, 0, 0)) StartCoroutine (Delay ()) void Update() if (obj Randomize 0 .transform.rotation.eulerAngles.y lt 90 obj Randomize 1 .transform.rotation.eulerAngles.y lt 90) obj Randomize 0 .transform.RotateAround (obj Randomize 1 .transform.position, Vector3.up, Time.deltaTime 100) obj Randomize 1 .transform.RotateAround (obj Randomize 0 .transform.position, Vector3.up, Time.deltaTime 100) I can make this game but when rotating finish they aren't Directed. this video link describe my problem and this is unity package of my game. how can I use mathf clamp RotateAround for stopping rotation?! |
0 | Check whether a vector is to the left or right of another position I don't know how to decide if my point is on the left or right side of another object. My first thought was to check if x axis of object1 is bigger or smaller than object2's, but if my objects rotate then that isn't working. In the picture above we have two states where object2 is on the left side of object1. In one case its x coordinate is greater, in the other, its x coordinate is less. |
0 | How to implement Vector3.MoveTowards follow with random movement I want to implement an AI behavior where an enemy runs towards the player while sidestepping randomly and aggressively (like in this video https www.youtube.com watch?v 35Ut C4eL40) Currently I am just using Vector3.MoveTowards but that results in smooth movement which isn't exactly what I need. I've tried adding an offset to the target using Random.insideUnitCircle but it just doesn't work. If anyone could give me an algorithm to implement it'll be great. Thanks |
0 | Rotating a button in Unity UI by 180 on the Y and it stops working If I rotate my button by 180 on the Y axis I can't even click on it. If for example I rotate it 180 on the Z axis everything is fine. Why does this happen and how can I fix it ? |
0 | Conditional Variables in Scriptable Objects While using ScriptableObjects, how can I make some variables conditional? Example Code System.Serializable public class Test ScriptableObject public bool testbool public string teststring public int testint Goal When testbool true then teststring is available to edit, when testbool false then testint is available to edit while the other one is "grayed out". |
0 | Corgi Engine Character glitches with "jump" animation on top of a ladder I'm new to Corgi Engine and Unity in general. I have an issue that I could find a way to resolve. I'm using CorgiEngine's quot RetroLadder quot prefab and extended quot Rectangle quot character with custom animations from quot MinimalLevel quot The problem is that when character finishes climbing the ladder, for a very short amount of time, jump animation appears. As in my case jump animation is very different from idle animation, this feels like an unpleasant glitch to me, so that's why I want to fix it. You can see it on the GIF below (at first I jump near the ladder to show how animation looks and then start climbing the ladder and on the top jump glitches) I checked some other demos (e.g. RetroVania, which uses some ladders there) and they also have this quot glitch quot with Corgi demo character, but as the character's idle and jump animations are not very different, it doesn't seem wrong (GIF below) I suspect that this glitch happens because quot CharacterLadder.cs quot script disables gravity during ladder climbing and then enables it back which triggers fall of the character Do you think it's possible to workaround it somehow? Thanks! |
0 | Why do these textures tile rather than just overlap? It might help to provide all the details, so here is the YouTube tutorial which sparked my question. There's a prefab of the background tile called "Tile Background." This prefab has the default settings, except that Pixels Per Unit is set to 512, and that it has a script attached to it called BackgroundTile which hasn't even been opened. It's just there for the other script to reference. An empty object was created called Board, which has Tile Background as its tile prefab. It also has a script, Board.cs, the contents of which are here using System.Collections using System.Collections.Generic using UnityEngine public class Board MonoBehaviour public int width public int height public GameObject tilePrefab private Backgroundtile , allTiles Start is called before the first frame update void Start() allTiles new Backgroundtile width,height Setup() private void Setup() for(int i 0 i lt width i ) for(int j 0 j lt height j ) Vector2 tempPosition new Vector2(i, j) Instantiate(tilePrefab, tempPosition, Quaternion.identity) Width is set to 4. Height is set to 7. Other than that, the camera position is X 1.5,Y 3 and the aspect ratio is 9 16. My question is this why, when this is run, does Vector2(i,j) get interpreted as tiling the sprites, rather than placing the sources of the sprites in a 4x7 pixel grid, where they overlap almost entirely? There's no place where their positions get multiplied by the size of the tiles, right? Halving the pixels per unit doesn't even just halve the height of the board it stays a constant size and looks really weird, despite the board not having set dimension attributes. What's going on here? |
0 | Loading encounters and collisions questions within 2D I had three basic questions regarding the creation of a 2D sandbox openworld game much like Terreria. Only looking for a general overview opinion, nothing too detailed. Any links to literature that would help answer the questions below would also be helpful. First off Keeping track of the map using regions chunks, lets say 512 x 512 chunks. Is it recommended to pre load the surrounding chunks of the 'chunk in focus', so if the character enters either one there is no load time? Or do you simply load smaller slices of the chunk next door, in the direction of movement? Secondly. Do I need to add a collision box to every tile that is preloaded so any NPCs that are off screen but 'next door' can interact with the environment? Or is this going to be massively CPU intensive ? (512 x 512 x 9 tiles alone) Third and last question. Off screen RANDOMDLY GENERATED NPCs monsters I assume dont load and render as they enter the viewable area on the active chunk but are loaded and activated sometime before they are seen. What are the general strategies use to handle this? For Reference Using c with Unity, no third party frameworks plugins. Many thanks John |
0 | Unity PoolingSystem failing to instantiate I am wanting to spawn monsters into my scene in Unity. I was told to use a Pooling System, so I got the free one Unity offers in the Asset store. I have followed the little documentation that there is, and am encountering an error. I do not know if I am just missing something but I am getting an object reference not set error. NullReferenceException Object reference not set to an instance of an object PoolingSystem.InstantiateAPS (System.String itemType) (at Assets Advanced Pooling System PoolingSystem.cs 104) MobSpawner.Start () (at Assets Scripts MobSpawner.cs 16) It throws this on the following code private PoolingSystem poolingSystem Use this for initialization void Start () poolingSystem PoolingSystem.Instance poolingSystem.InstantiateAPS("Resources EnemyPrefabs Skeleton") Could someone please guide me in the right direction or tell me what is wrong here? |
0 | Visual studio alternatives for unity as intellisense not working I am new to unity and unity tools for game dev are unavailable in vs community,i also tried vs code.So what are some alternatives for vs for unity scripts for a beginner? |
0 | One side of every object is black I'm trying to make a driving game in Unity, but recently have been having lighting issues. When I was first building it, the lighting worked fine. However, recently, one side of everything (the indirect lighting side) has turned black. Here's an image of the issue. I've tried changing my lighting settings, but can't seem to fix it. Here are my lighting settings. What can I do to fix this? (I am using Unity 2017.2.0f3) |
0 | Getting Image From Android to Unity3D I am trying to get an image from the user gallery and import it in unity. I have written a native plugin in Android Studio and exported JAR as it s needed for the native stuff to get working. I am successful in opening gallery but I don t have an idea how do I get that image retrieved from OnActivityResult in Java File and use it in C for Unity. Any help and ideas will be highly appreciated. |
0 | How to "amplify" a force and physic using AddForceAtPosition? I have the object in the image. The red box is kinematic when an object hit it , i set kinematic to false, so Unity apply normal physic. But I would like to apply also a force to the point indicated by the violet cross. So I'm using Rigidbody.AddForceAtPosition rb.AddForceAtPosition (ForceDirection ForcePower, PointForcePosition.transform.position, ForceType) PointForcePosition is an empty GameObject child of the red box object, placed where violet cross is pointing. My question are Force Position can I use that approach (an empty gameObject placed where i want to apply force ) ? Force Direction is it corret a Vector3 ( 0 , 1 , 0 ) to indicate a down force Which ForceMode is the best for my purpose ? Impulse ? Force ? Thanks |
0 | Downsides of using a 8192 x 8192 texture? So I am using Unity to build a 2D game and one thing that I needed is to be able to render a lot (talking about 10s of thousands) of sprite to the screen so I have a custom solution that basically is a single game object with a script that uses Graphics.DrawMesh() with pretty good results right now. Now I know another way to reduce draw calls is to have a few materials as possible (as I believe a single mesh can only use 1 material) so I was think about using a 8192 x 8192 texture as basically my main (maybe only texture) as with 64 x 64 sprites, I can fit a bit over 16000 sprites which should be more than enough for all the sprites in the game world). My question is whether or not there is any major downside of using a texture of this size? I am sure there are decides and video cards that would not support this but I am curious as to what those are. Would current gen next gen consoles support this? At what point would video card not support this? For the game I am working on mobile VR is not a concern. If this texture size would restrict support too much, what about 4096 x 4096? |
0 | Spawning random objects at random positions in the 3D world My main character can move horizontally and not vertically. It can move from x 4 to 4 and z 4 to 4 (a square area). I don't want objects to spawn where my character can move but every where else. I wrote the following script. According to me it should have worked perfectly fine. But, I can't figure out why the objects are still spawning in the perimeter where the main character is present. public class SpawnGameObjects MonoBehaviour public float secondsBetweenSpawning 0.1f public float xMinRange 25.0f public float xMaxRange 25.0f public float yMinRange 5.0f public float yMaxRange 0.0f public float zMinRange 25.0f public float zMaxRange 25.0f public GameObject spawnObjects what prefabs to spawn private float nextSpawnTime void Start () determine when to spawn the next object nextSpawnTime Time.time secondsBetweenSpawning void Update () exit if there is a game manager and the game is over if (GameManager.gm) if (GameManager.gm.gameIsOver) return if time to spawn a new game object if (Time.time gt nextSpawnTime) Spawn the game object through function below MakeThingToSpawn () determine the next time to spawn the object nextSpawnTime Time.time secondsBetweenSpawning void MakeThingToSpawn () Vector3 spawnPosition get a random position between the specified ranges spawnPosition.x Random.Range (xMinRange, xMaxRange) spawnPosition.y Random.Range (yMinRange, yMaxRange) spawnPosition.z Random.Range (zMinRange, zMaxRange) if ((spawnPosition.z lt 4 amp amp spawnPosition.z gt 4) (spawnPosition.x lt 4 amp amp spawnPosition.x gt 4)) MakeThingToSpawn () determine which object to spawn int objectToSpawn Random.Range (0, spawnObjects.Length) actually spawn the game object GameObject spawnedObject Instantiate (spawnObjects objectToSpawn , spawnPosition, transform.rotation) as GameObject make the parent the spawner so hierarchy doesn't get super messy spawnedObject.transform.parent gameObject.transform |
0 | How can I convert an html5 web game to an android app? I have already made an html5 game and it is in service. I want to service this at Android app too. I know little about Java or Kotlin, so I think the least risky way is to use a webview. There is already a function to save game data with Oauth authentication. I thought this part should be replaced with google play Oauth. However, there is a problem that the app does not run when the player is offline. (Run the app fails to load any html document) However, if you load a local html file, it will be rejected from the existing firebase SDK because there is no domain. In fact, I know very little about native app development, so I don't know that what I don't know, what I need. What should I do in this situation? Do I need to rebuild my app in Kotlin or Java from scratch? Do I have to use the same engine as Unity? Do I have to rebuild with a framework like cordova? The question may not fit here, but I need help. Please. |
0 | What's the "right way" to open a websocket connection inside WebGL? The official Unity documentation says that, to run websockets in the WebGL player, you should use this plugin on the Asset Store. Unfortunately, following that link leads to a notice that this asset has been deprecated and is no longer available, with no explanation as to why or what should be done to replace it. With that unavailable, how should I implement WebGL websockets in my game? |
0 | 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)? |
0 | How Client send info to Host in Unity Multiplayer I want to send player name and other details from client to host device. I have setup game for maximum two players connection. Here is the code that I have tried multiple times with different changes void Start () spriteRenderer GetComponent lt SpriteRenderer gt () circleCollder GetComponent lt CircleCollider2D gt () StartCoroutine (ColorSwitcher ()) InitialTasks () private void InitialTasks () isAlive true GameManager.Instance.IsPlayerWin false int selectedTheme Random.Range (0, ballSprites.Length) spriteRenderer.sprite ballSprites selectedTheme trailRenderer.material trailMaterials selectedTheme destroyParticleObj.GetComponent lt ParticleSystemRenderer gt ().material trailMaterials selectedTheme hidePlayerName OnTouchHidePlayerName if (!isLocalPlayer) remote player gameObject.tag GameConstants.TAG REMOTE PLAYER else local player Debug.Log ("locally set player name " DataCollection.localPlayer.PlayerName) playerNameText.text DataCollection.localPlayer.PlayerName StartCoroutine (SomeDelayForSendingPlayerDetails ()) if (isServer) RpcSetRemotePlayerName (DataCollection.localPlayer.PlayerName) else CmdSetRemotePlayerName (DataCollection.localPlayer.PlayerName) public override void OnStartLocalPlayer () base.OnStartLocalPlayer () CmdSetRemotePlayerName (DataCollection.localPlayer.PlayerName) ClientRpc private void RpcSetRemotePlayerName (string remotePlayerName) playerNameText.text remotePlayerName Debug.Log ("rpc remote player name " remotePlayerName) Command private void CmdSetRemotePlayerName (string remotePlayerName) RpcSetRemotePlayerName (remotePlayerName) Debug.Log ("cmd remote player name " remotePlayerName) Basically I want to interchange names of both players in 2 players multiplayer game. So please give me some advice into this. |
0 | How to stop jumping again when 3D character is in air (double jump)? I'm working on simple rpg and having some trouble with player jumping. I'm trying to use unity's raycast to check colliders under the player before jumping again. The problem appears that no matter how many tweaks I make to the distance or the validation of the canJump function, the raycast the player seems to at max jump twice. At lower levels the player can even hover if timed correctly. Could someone overlook my code since it appears that I might have a noob glitch somewhere? using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour public float speed public float jumpForce public float turningSpeed private bool canJump void Start() void Update() RaycastHit hit if (Physics.Raycast(transform.position, Vector3.down, out hit, 1.01f)) canJump true ProcessInput() void ProcessInput() if (Input.GetKey("right") Input.GetKey("d")) transform.position Vector3.right speed Time.deltaTime if (Input.GetKey("left") Input.GetKey("a")) transform.position Vector3.left speed Time.deltaTime if (Input.GetKey("up") Input.GetKey("w")) transform.position Vector3.forward speed Time.deltaTime if (Input.GetKey("down") Input.GetKey("s")) transform.position Vector3.back speed Time.deltaTime if (Input.GetKeyDown("space") amp amp canJump) canJump false GetComponent lt Rigidbody gt ().AddForce(0, jumpForce, 0) |
0 | How can I optimize the size of my .apk? I noticed that the Flappy Bird .apk is only around 900 KB. I'd like to know how I can achieve a similar optimization in .apk file size for my own games, which use Unity. A small single scene game developed with Unity will have an .apk size of nearly 10 MB, in comparison. |
0 | how to reset etsa function GetJoystickNames in unity? the problem is that if I connect a command the array GetJoystickNames increases an index but if you disconnect it does not reduce the index and continues counting as if it were connected |
0 | Why doesn't my C 6 code compile in Unity? Why can't Unity work with C 6 code? It always gives me compiler errors. Here are some code examples using static System.Convert using static System.Environment " punten NewLine Money NewLine KilledEnemies NewLine bonus NewLine total " I use Visual Studio as my code editor and build with no errors. If I press play in Unity it won't build. |
0 | Unable to add asset sprite, not sure why I'm using Unity and have a 2D project. I'm trying to add a background image to my project scene, but I'm unable to. Adding smaller .png files to the project work fine, by simply dragging them onto the Hierarchy tab. My background image, and larger images, do not work though. Below is the image in question It's a 66kb png. Nothing weird about it. How should I be adding it as a background if I'm unable to add it as a sprite? Below is the assets settings under Import Settings |
0 | How to stop several coroutines running on array of game objects In the code below, I am running a coroutine on each element of an array of game objects. How can I stop running the FadeToForEnemy coroutine on each game object? IEnumerator EnemyCycle() while (isRepeating) for (int j 0 j lt enemies.Length j ) Enemy currentEnemy enemies j var myMaterial currentEnemy.GetComponent lt Renderer gt ().material var currentFade StartCoroutine(FadeToForEnemy( myMaterial, 0f, 1f, currentEnemy.gameObject, false)) yield return new WaitForSeconds (hdTime) for (int j 0 j lt enemies.Length j ) Enemy currentEnemy enemies j var myMaterial currentEnemy.GetComponent lt Renderer gt ().material var currentFade StartCoroutine(FadeToForEnemy( myMaterial, 1f, 1f, currentEnemy.gameObject, true)) yield return new WaitForSeconds (srTime) UPDATE I tried stopping the coroutines in the following but the cycle of fading in and out just continued. public void StopEnemyCycles () for (int i 0 i lt enemies.Length i ) enemies i .StopAllCoroutines () StopCoroutine ("EnemyCycle") Also below is FadeToForEnemy IEnumerator FadeToForEnemy(Material material, float targetOpacity, float duration, GameObject gameObj, bool isEnabled) Cache the current color of the material, and its initiql opacity. Color color material.color float startOpacity color.a Track how many seconds we've been fading. float t 0 if (isEnabled) gameObj.GetComponent lt BoxCollider2D gt ().enabled isEnabled while(t lt duration) Step the fade forward one frame. t Time.deltaTime Turn the time into an interpolation factor between 0 and 1. float blend Mathf.Clamp01(t duration) Blend to the corresponding opacity between start amp target. color.a Mathf.Lerp(startOpacity, targetOpacity, blend) Apply the resulting color to the material. material.color color Wait one frame, and repeat. yield return null if (!isEnabled) gameObj.GetComponent lt BoxCollider2D gt ().enabled isEnabled I have several groups of enemies, each group fades in and out at the same time. |
0 | Why isn't my tilemap collider appearing? I am trying to make a 2d game but my player falls through the tilemap every time. My tilemap collider doesn't seem to show up. What is going on and how do I fix this? The first image is rigidbody currently falling through the tilemap and the tilemap. The second image is rigidbody currently falling through the tilemap and the rigidbody. |
0 | How can I turn off the sound from another scene? I attached music file to my first scene and thanks to following javascipt code, sound continues without stopping in other scenes. public static var object SingletonMusic null function Awake() if( object null ) object this DontDestroyOnLoad(this) else if( this ! object ) Destroy( gameObject ) My problem is that I want to turn off the sound from the button in the another scene (setting scene) so that I added a new button to my setting scene and attached the following javascript code to the button that I have created. Javascript code var objects AudioSource SingletonMusic.object.GetComponent(AudioSource) if( objects.isPlaying ) objects.Pause() else objects.Play() However, it gives following errors If I start the game from Setting scene I get this error If I start the game from first scene and then, go to Setting scene I get this error |
0 | Camera is centered on character, but doesn't show character in game window I'm using Unity 4.6.3. I create an animation from sprite. When I press Play button, I see animation plays on scene window, but on Game Window, I don't see anything. Here is Inspector for main camera Here is Inspector for Player I have checked that both z 0 when execute. Please tell me which part I config wrong ? |
0 | ForceMode in AddTorque in Unity game development In UNITY game development platform while programming in C I came across a method to add torque to component public void AddTorque(float x, float y, float z, ForceMode mode ForceMode.Force) In this Function what is meant by ForceMode? |
0 | Can I force a manually created texture to not be divided with low quality? I have a texture that I have created that looks something like this . This is a very low texture map, but it helps me in a shader that I'm making that distinguishes between land and ocean, the ocean tiles do different things than the land. To try and figure out what was going on, I used the shader to turn the ocean, as defined by the mask, black. Note that this image doesn't match the ocean texture example from above, but it's the best I had... The ocean is a binary color, either it is ocean or isn't, and is set appropriately. But what I'm actually seeing is that if the 2x2 tile area has mixed land ocean, the value is averaged. What I've noticed is that the pixels were combining together, a 2x2 pixel area was averaged. After tracing through this for some time, I discovered that the issue was a quality setting that reduced the resolution of certain images. There are some images that I don't mind lowering the resolution of, but images such as this one I absolutely don't want to lower the resolution. Is there a setting that I can add to a runtime generated texture to tell it not to reduce it's resolution if requested to by the quality settings? EDIT Code fragments to produce the results above. It's kind of hard to pull just the fragments that produce this code and not produce an overwhelming bit, but hopefully this will do. Code to generate textures Color32 windMask new Color32 world.width world.height for (int x 0 x lt world.width x ) for (int y 0 y lt world.height y ) windMask x world.width y world.Tiles(x, y).baseType Tile.BaseType.Ocean?new Color32(255,255,255,255) new Color32(0,0,0,255) sharedMaterial.SetTexture(" WindMask", TextureUtilities.TextureFromColors(world.width, world.height, windMask, FilterMode.Point)) public static Texture2D TextureFromColors(int width, int height, Color colors, FilterMode filterMode FilterMode.Trilinear) Texture2D texture new Texture2D(width, height) texture.SetPixels(colors) texture.filterMode filterMode texture.Apply() return texture The Shader code o.Albedo 1 tex2D( WindMask, IN.uv MainTex).r The "Fastest" quality settings that show the issue The "Fantastic" quality, which correctly isolates the ocean. Image of the correctly isolated ocean The issue is the "Texture Quality", which you will note for the fastest setting is half resolution. I would really like to keep the ability to use lower resolution in the game, but have a few textures that do not use the lower resolution if the quality settings change. |
0 | Optimal way to select a random item from a list based on its chance to appear in Unity I am creating a random object spawning script in Unity with c , and am wondering what the ideal way to do this task would be. So I have a list of 31 objects or so, of my special class type. Each one has an arbitrary number assigned as it's weight. This number is divided by the sum of all their weights and multiplied by 100 to make their percent chance for appearing. It's at this stage where I'm stumped. How should I go about selecting them with a random number between 0 and 100? My first idea was to give each one a range and if the random number falls within it, I select that one, but that method does not sound like it would be the most elegant and would involve like 31 IF statements. What is the standard way to do this sort of random selection? |
0 | Changing animation speed at runtime Is there a way in Unity to change the animation speed of an animation managed by an animator controller (Mecanim)? I'd like to do that at runtime so that I can speedup and slow down an animation based on conditions in code. |
0 | Why do I have render problems happening frequently in my Unity scene? I am making vertical endless runner. My platforms are moving down, and the camera and players are remaining in the same location, resulting in the effect of player movement. The obstacles are generated and move in same direction as platforms. The problem is obstacles rendered by the camera is not right. I mean that the obstacles are in camera's FOV but are still visible after some time when they reach the player to close. |
0 | Colliders slightly intersecting each other any solution? Consider this simple scene In Unity, colliders slightly intersect each other. Typically, this isn't a problem. However, I want to make a custom character controller using a box collider and not a capsule collider. In the above scene, the floor is divided into 2 objects, each with their own collider. The playercontroller has their own box collider. And the problem if the box collider moves forward, it will clip with the seam on the floor, even though both floor objects have the same height. The box will stop moving as if it has run into a wall. If I keep adding force to the box, it will never move forward. It will stay stuck on the seam this only exists because the box is slightly inside the first floor collider, and it will hit the second collider of the floor like a wall. This only occurs because of collisions clipping. With most playercontrollers, a capsule collider is used and thus this problem doesn't exist. Is there a workaround? How can the box smoothly move across the floor without colliding with the seam? Notes This does occur with capsule colliders but rare and is not very noticeable. A possible solution would be to merge all the colliders of the scene into one, unified collider. It is extremely tedious and has its drawbacks. This occurs if I am moving the collider with both MovePosition(), AddForce(), or modifying the velocity position of the transform. |
0 | Why are transform values in inspector different from animation tab? I m trying to make animation in timeline. But transform values in animation tab and inspector are different from each other. It causes problem when try to rotate player. It doesn t rotate the way I want. |
0 | Accessing a char array from another class I'm working on a crossword puzzle game. In order to set the letters in my tiles, I have a script attached to text components that accessing a char array that stores my letters. It looks like this First class public class GenerateBoard MonoBehaviour public static char , gameBoard new char 15,15 void Start() gameBoard 0, 0 'W' Second class public class SetLetter MonoBehaviour Text letter public int x public int y Start is called before the first frame update void Start() letter GetComponent lt Text gt () letter.text GenerateBoard.gameBoard x,y "" Update is called once per frame void Update() Debug.Log("glitch " GenerateBoard.gameBoard 0, 0 ) I would expect Debug.Log to print 'W' but it appears to be empty. Why isn't it accessing the letter 'W' from the first class? When I use Debug.Log in my first class it properly prints 'W'. |
0 | Can both High poly model go with a low poly scene? I'm in the process of developing a game, and I've found a model that would go perfectly for the character. However, the scentre I already have is low poly and I can't find a good enough high poly to go with it. So tell me whether or not I should I should carry on with the art I have or find a low poly model. |
0 | Destroy physics triggered GameObject in Unity ExecuteInEditMode To destroy GameObjects I'm using this code try DestroyImmediate(g) catch (Exception e) Destroy(g) It is giving me error, something like this Full code using System 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 () void Start() void OnValidate() foreach(GameObject g in gameObjects) try DestroyImmediate(g) catch (Exception e) Destroy(g) gameObjects.Clear() foreach (Vector3 point in points) GameObject tem GameObject.CreatePrimitive(PrimitiveType.Cube) tem.transform.position point tem.transform.localScale new Vector3(0.1f, 0.1f, 0.1f) tem.transform.parent gameObject.transform gameObjects.Add(tem) |
0 | Unity Mathf.Lerp() didn't work as expected? I want to rotate an object 360 degrees so this is what I did xRotation Mathf.Lerp(0, 360, Time.fixedDeltaTime lerpTime) and then I used Quaternion.Lerp() to rotate the Object so targetRotation Quaternion.Euler(initialRotation.x xRotation, initialRotation.y, initialRotation.z) transform.rotation Quaternion.Lerp(transform.rotation, targetRotation, Time.fixedDeltaTime lerpTime) But it didn't work as expected, the xRotation didn't go from 0 to 360, it just changed from 0 to 9 (instantly), and that's it, it never changed. This is my full code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class QuaternionExpirement MonoBehaviour SerializeField Range(5, 10) float lerpTime Vector3 initialRotation bool mousePress, readyToRotate float xRotation private void Awake() initialRotation Vector3.zero mousePress false readyToRotate false xRotation 0 private void Update() mousePress Input.GetMouseButtonDown(0) private void FixedUpdate() if (mousePress) initialRotation transform.eulerAngles readyToRotate true if (readyToRotate) xRotation Mathf.Lerp(0, 360, Time.fixedDeltaTime lerpTime) Quaternion targetRotation Quaternion.Euler(initialRotation.x xRotation, initialRotation.y, initialRotation.z) transform.rotation Quaternion.Lerp(transform.rotation, targetRotation, Time.fixedDeltaTime lerpTime) if (xRotation gt 360) readyToRotate false |
0 | How to drag my dragging object in 'game' unity? I have made a dragging sphere which drags, problem is how can I drag it using keyboard keys , I dont want to build it again on iphone simulator after experimenting with my code. for dragging it is not accepting mouse or any keyboard keys. Is it possible ? |
0 | How do I prevent floating and jittering when on the ground and using spherical gravity? TL DR My ship floats and jitters when it lands on a sphere. To elaborate on the title I'm experimenting with a 3D space game. I have created a sphere, which in turn has a larger sphere overlapping it, within which, gravity will take place. However, once my player's ship (currently using an arrowhead) lands on the planet, it doesn't actually make contact with the surface of the sphere, and then the ship begins to rotate erratically and jitter. Code below. private void OnTriggerStay(Collider other) if (other.CompareTag("SoI")) inSoI true This trigger checks to see if the ship is in the larger overlapping sphere. I have another identical block for OnTriggerExit which sets inSoI to false. I also have a OnCollisionEnter which sets another variable, landed to true, and a OnCollisionExit which sets it to false. private void FixedUpdate() if (inSoI amp amp !landed) gravityVector (planet.transform.position transform.position) rb.AddForce(gravityVector.normalized planetrb.mass rb.mass gravityVector.sqrMagnitude) Simply, if in the larger sphere, then accelerate towards the planet. I tried disabling gravity if in contact with the sphere. It removed a lot of the jitter, however it still floats, and it still rotates side to side. The sphere by the way, is the standard Unity sphere, scaled 10000x in every axis. I don't need code (though it would help), any solution is fine, even if it means abandoning the project. |
0 | Should I ask my artist to make Sprites in full resolution or can I scale them up? I'm started with Unity development and my artist asked me what size she should make the sprites for the game. They are all pixel art and she didn't know if she should make them on Photoshop on a small resolution, do them already on the iOS resolution 1920x1080 or even if she should use a vector program and then rasterize them. How is this normally done? |
0 | How to not freeze the main thread in Unity? I have a level generation algorithm that is computationally heavy. As such, calling it always results in the game screen freezing. How can I place the function on a second thread while the game still continues to render a loading screen to indicate the game is not frozen? |
0 | pathFinding performance in Unity3d I am making Sniper game in unity 3d. In this game zombies will come randomly towards the sniper and sniper have to kill them. I am using RAIN(indie) for path finding. It works best when zombies are few . As I increase the Zombies( that is 10) the performance decrease a lot. The fbs drops to 25. I want to know is there any technique or steps so I can improve fps Any other technique algorithm that I can use for pathfinding weith good fps. PS I already remove Sensor component from AI. FPS of game without AI is 61 |
0 | Effect only on one object (two cameras) I have a problem. I want a Grayscale effect to be applied ONLY to the chair on the stage. The chair has a layer CurrentItem. And I have two cameras Camera All renders everything except layer CurrentItem (I set this exception in CullingMask) Camera CurrentItem Finally I need to apply not just one effect, but a few. |
0 | Animator Panel in Unity Where is "Entry"? I am following a tutorial on Unity, and I saw a screenshot like the following When I reproduced the steps of the tutorial, I realized that the green quot Entry quot box was not present on my screen. I have been thinking why this could be and the only reasons that I could think of are The tutorial skipped a step I have something misconfigured In the latest version of Unity that box has been erased or replaced Which one is it? Did I forget a 4th option? PS If it is option 3, could someone explain me what was this feature for, and what has it been replaced with? UPDATE I am using Unity 4.6.2f1 |
0 | What is grid in Unity and how can I implement it? I'm a beginner. I need to place a grid on my map in Unity and would like to access it to place a simple object on mouse click. How can I achieve this ? I am unable to understand the grid functionality, should I have to write code for a 2D array or is there something in Unity that I can access, and what is basically the grid like something when I click my background image ? |
0 | Optimal solution to render sprites with transparent edges in Unity Since I'm currently developing a 2D game for mobiles, overdraw and drawcall count is my first priority in the design of the application I've thought initially to split each sprite in two parts one where each pixel is fully opaque (to render with cutout shaders in front to back order) and the other part with semi transparent edges (which will be ordered back to front) Since I need to support ES2.0 devices, I can't use texture arrays and I need to fit as many sprites as possible in a single 2048x2048 texture atlas to reduce drawcalls and ensure mobile compatibility, but as you can see from this picture Splitting sprites in opaque and non opaque parts will certainly double the space occupied in the atlas, thus decreasing by half the potential amount of consecutive sprites I can draw in a single drawcall This way, I'm paying drawcalls to reduce overdraw. By rendering the entire sprite with transparent shaders I'd pay overdraw to reduce drawcalls. Am I missing something? Is there a better approach? |
0 | Why is Unity ignoring my camera on Android? I am making a TV remote app for a specific android device (the Pixel XL, 1440x2560 resolution). However, when I put the app on my phone, it truncates most of the app. Here's what it should look like Here's what it ends up looking like My game is forced in portrait, and I want to keep it that way. I have tried rotating the canvas, but that does nothing. The Android app also seems to ignore the main camera I think it is just using the canvas. I tried many different things, including changing the scaling and setting the anchors. None of this had any effect. I have even set the editor Game window to the target resolution, but it appears to work via the editor. Why is Unity ignoring my camera on Android? |
0 | How to make a 2D sprite slowly vanish as it crosses a line as if disappearing behind a wall? ...Except there is no wall. Only one of its edges. Here is what I mean. Notice how the lines "sink" into the center square. I've been trying to do something very similar, in Unity. My approach is to detect when the lines come into contact with the center square (hexagon, in my case), and first initiate an animation that decreases the width of the lines, precisely timed via math to last exactly as long as needed. But there's a problem. The animation doesn't play. I've spent the last few hours debugging it, to no avail, and now have finally given up, because the problem is too complex to post here. Too many variables. Are there any better methods of achieving this? My own, even if it had worked, wouldn't have been perfect, because the width would've decreased on both sides (of the line running in the middle of the thick squares or hexagons that are to disappear), giving it a strange, swallowing effect, but I'd be satisfied, since it's just a practice project. So, I'm giving up on this approach. What are easier ways to do this? (Preferably in Unity, but I'll take anything.) Hasty edit Keep in mind that my "lines" are not sprites but line renderers, but I'm looking for ways to work on either. |
0 | Lighting doesn't work properly in WebGL build only at one place So I have a 2d game where a player walks around the level (top view) with a flashlight in front of him. Everything works fine in the editor, however whenever I build it for WebGL and test it in my browser, one room only one, has a problem with lighting, and as I walk in different parts of the room lighting changes in a weird way, and the floor is blinking in the first half of the room, as well as the flashlight is barely visible (if at all). Here's how it looks in the editor and is supposed to look like And here's a few screenshots from the web build P.S. Everything works fine in a standalone build. Also there seems to be no problem when I disable the 4 lights (the whole room works fine), these are the lights (the ones that look like from a window) |
0 | How to modify a property after animating it in Unity3D? I animate localPosition. The animation works well, but after, I can't change a value of localPosition in editor or code. I want to change a value after the animation completes, not at the same time. I use Animator with AnimationClipPlayable. I create Animator in editor and the rest in code (AnimationClip, AnimationClipPlayable, AnimationCurve). The animation animates a property from one position to another. It finishes, I don't do anything to stop the animation. Let me know, if you need a code example or video presentation. |
0 | Unity Pink Texture On WebGL I'm trying to follow a youtube tutorial for my new game(images puzzle) and by using it's implementation on github to upload it later on facebook. When I run the game inside unity editor its work without any problem, but when I export the game to exe or WebGL I get pink images background instead of the image am using. Youtube tutorial link here. GitHub repository link here. The game works Fine inside unity But shows pink images on web browsers and exe games Why the images are showing pink background? |
0 | Explaining Unity Sprite Default Shader I would like to know why we would use alpha blending in that shader for just rendering a sprite, which is just a texture ? What is tint color ? Why we multiply the alpha value by the color here ? fixed4 c tex2D( MainTex, IN.texcoord) IN.color why ? c.rgb c.a why ? Shader "Sprites Default" Properties PerRendererData MainTex ("Sprite Texture", 2D) "white" Color ("Tint", Color) (1,1,1,1) MaterialToggle PixelSnap ("Pixel snap", Float) 0 SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" "PreviewType" "Plane" "CanUseSpriteAtlas" "True" Cull Off Lighting Off ZWrite Off Fog Mode Off Blend One OneMinusSrcAlpha Pass CGPROGRAM pragma vertex vert pragma fragment frag pragma multi compile DUMMY PIXELSNAP ON include "UnityCG.cginc" struct appdata t float4 vertex POSITION float4 color COLOR float2 texcoord TEXCOORD0 struct v2f float4 vertex SV POSITION fixed4 color COLOR half2 texcoord TEXCOORD0 fixed4 Color v2f vert(appdata t IN) v2f OUT OUT.vertex mul(UNITY MATRIX MVP, IN.vertex) OUT.texcoord IN.texcoord OUT.color IN.color Color ifdef PIXELSNAP ON OUT.vertex UnityPixelSnap (OUT.vertex) endif return OUT sampler2D MainTex fixed4 frag(v2f IN) SV Target fixed4 c tex2D( MainTex, IN.texcoord) IN.color c.rgb c.a return c ENDCG |
0 | Physics.CheckSphere() appears not to work in Unity My scene is simple, I have a single GameObject with the following script attached usings ... public class GalaxyManager MonoBehaviour public int numberOfStars 300 public int maximumRadius 100 public float minDistBetweenStars 2f void Start() for (int i 0 i lt numberOfStars i ) float distance UnityEngine.Random.Range(0, maximumRadius) float angle UnityEngine.Random.Range(0, 2 Mathf.PI) Vector3 cartPosition new Vector3(distance Mathf.Cos(angle), 0, distance Mathf.Sin(angle)) if (!Physics.CheckSphere(cartPosition, minDistBetweenStars)) GameObject star GameObject.CreatePrimitive(PrimitiveType.Sphere) star.transform.position cartPosition else i Update is called once per frame void Update() What this is supposed to do is generate 300 quot stars quot within the maximumRadius of 100 that are separated by at least minDistBetweenStars. I haven't been able to figure out what's actually happening sometimes the check finds a collider and sometimes it doesn't. It's almost as if the CheckSphere() check is happening before the stars get placed via the star.transform.position cartPosition. I'm very new to Unity and appreciate the help. Anyone have any idea what's going on? edit Some more information, I've tried the script in both 2020.1.12f1 and 2019.4.14f1 to no avail. I'm also aware that this will lead to an infinite loop if it can't find a placement. |
0 | Retrieve the original prefab from a game object How would one proceed to retrieve the original prefab used for instantiating an object? In the editor these two functions work Debug.Log(PrefabUtility.GetPrefabParent(gameObject)) Debug.Log(PrefabUtility.GetPrefabObject(gameObject)) But I need something that works in the release version. I have objects that can be transported between scenes ands I need to save their data and original prefab to be able to instantiate them outside of the scene they have been originally instantiated. ie Game designers create new prefabs. Game designers create objects from prefabs and place them in scenes (50 to 150 scenes). Game is played and objects are moved across scenes. Game is saved and infos about objects which have moved are saved in the save streams (files or network). This is where I got stuck. Currently, to palliate to the shortcomings, we're saving the name of the prefab in the prefab. But each time a prefab is moved, renamed or duplicated the string must be changed too, sometimes the objects created from the prefab keep the original name (game designer might have edited the prefabPath field). Maybe there is a better way to achieve proper save games without having to access to the original prefab name. But currently we keep the saves segmented on a per level basis (easier and safer to save load to files and transfer the save games to from servers) |
0 | Unity 2D map and walkable collisions I have a 2d player who can only walk on black area. There is a red collider so player can't walk past it. Player has capsule collider. The problem is player can't walk toward the edge with his feets becasue of the it's collider. But player would probably want to walk toward the edge. Here is a sketch I've made. Is there a way to tweak this ? |
0 | How can I find the center position of two or more objects? using System.Collections using System.Collections.Generic using UnityEngine public class MoveCameraBehind MonoBehaviour public GameObject camera public List lt GameObject gt targets new List lt GameObject gt () public float cameraDistance 10.0f public bool behindMultipleTargets false public string cameraWarningMsgs "" public string targetsWarningMsgs "" Use this for initialization void Start() if (camera null) var cam GetComponent lt Camera gt () if (cam ! null) cameraWarningMsgs "Gettig camera component." camera transform.gameObject else cameraWarningMsgs "Creating a new camera component." GameObject NewCam Instantiate(new GameObject(), transform) NewCam.name "New Camera" NewCam.AddComponent lt Camera gt () camera NewCam if(targets.Count 0) targetsWarningMsgs "No targets found." void FixedUpdate() if (targets.Count gt 0) MoveCameraToPosition() public void MoveCameraToPosition() if (targets.Count gt 1 amp amp behindMultipleTargets true) var center CalculateCenter() transform.position new Vector3(center.x, center.y 2, center.z cameraDistance) if (behindMultipleTargets false) Vector3 center targets 0 .transform.position targets 0 .transform.forward cameraDistance transform.position new Vector3(center.x, center.y 2, center.z) private Vector3 CalculateCenter() Vector3 center new Vector3() var totalX 0f var totalY 0f foreach (var target in targets) totalX target.transform.position.x totalY target.transform.position.y var centerX totalX targets.Count var centerY totalY targets.Count center new Vector3(centerX, centerY) return center The CalculateCenter function make the targets(objects) to change positions and vanish away far away. Even if there is only one single target. What I want to do is if there is one object for example one 3d cube position the camera behind the cube. And if there are more cubes for example two or ten and the camera is somewhere else calculate the middle position behind the targets and position the camera in the middle behind them. To show what I mean in this example the view(like a camera) is behind the two soldiers in the middle position between them from behind. But what if there are 5 soldiers how can I find the middle position and then position the camera behind them like this example in the screenshot ? |
0 | For Blender Unity users Would Blender's UV Project Modifier work in Unity? So, say in Blender you have a Cube that you put a "UV Project Modifier" on, with an Empty (controlled by a Bone) as the Projector. In Blender when you move the Bone, the UV moves on the cube. Great! But now let's say you wanted to bring that to Unity. Would that still actually work (being able to move the UV around with bone movement) or would it be busted? I'm trying to test it myself and it seems a dud but I already struggle with Blender's export process so wanted to check here. |
0 | How can I port my Gear VR app (Java, OpenGL ES) to Unity? I want to port my Gear VR app (created in Java using the official framework) to Unity, so I can also support Microsoft's new ish VR headsets (not talking about the Hololens!). In my current app I'm using OpenGL ES to draw everything I need (the app reads coordinates and additional information about what it has to draw from a .txt file), which is GL LINE STRIP The .txt file gives it a bunch of coordinate triples (x, y and z, so single vertices), it then has to automatically connects them (usually without loops) Kind of plane Either display a rectangular plane with a texture (using the Gear VR framework's "GVRSceneObject") OR create an outline (usually first point last point) that then gets filled in a specific color (GL TRIANGLE FAN) AND that is a little bit transparent if it includes concave areas, it's using GL TRIANGLES and the .txt file has coordinates for single triangles that have to be displayed at the same time and filled (it's still a single object mesh!) What I need Unity to do (with 1. and 2.) Display a couple of 1. (could be up to 50 or more) and 1 of 2. at the same time (there'll never be more than 1 of type 2.!) Remove all of 1. (that are displayed at the same time) or 2. from the scene and or replace them with a couple of different 1. or another 2. Group a couple of 1. together, so you can remove them at the same time (which would make stuff a lot easier) Read .obj files (including their texture) from internal storage (Android) or the HDD (Windows) and display it them instead of 2. (the .txt file includes the path to the file and texture) Everything has to happen at runtime, since the app doesn't come with any .txt files or pre imported .obj scenes objects! My question is How can I do this with Unity, targeting Windows and Android? |
0 | Problem with repeating objects in array when already in the array When the player move forward then paint is instantiate and stored in the array, even if the paint is already in the array it will again be stored in the array. But I don't want to repeat any paint in the array. public GameObject array public GameObject paint int temp 0 private RaycastHit hit public float speed 10f public Text levelText public GameObject paint float maxdistance 0.51f Vector3 newtargetposition bool pos private void FixedUpdate() if(Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward,out hit, maxdistance)) if (hit.collider.gameObject.tag "Obstacle") move false if (move) PlayerMove() public void PlayerMove() if (move) vector3 positions transform.position new Vector3(0f, 0.5f,0f) when player move then paint instantiate y position array temp Instantiate lt GameObject gt (paint, position, Quaternion.identity) temp newtargetposition position Debug.Log("newtargetposiiton " newtargetposition) if (temp 150) if (newtargetposition position) what can i do here i dont want to paint here because position store in newtargetposition,it is repeat array temp Debug.Log("newtargetpositions " newtargetposition) temp gameOver.SetActive(true) SceneManager.LoadScene(1) when player move forward store position in array when player move back already fillup position again store in array |
0 | Unity How to create C classes with different properties like Objects in javascript and put them in an array? I just started my gamedev journey on unity this week and while I have a background with coding, I'm still somewhat of a beginner. Last year I made a text UI based game on the web browser with javascript and have been trying to make the same game on Unity. One of the main features of my game is that you press a button to "go hunting" and I had an array filled with enemies that were objects with different properties such as health, mana, attack, etc... Then I'd randomly pick one of those objects from the array to be chosen as my enemy that I'd fight. I've been trying to figure out the best way to do this with C and I might just be overthinking this. As a bonus, I'd also like to be able to see the individual enemy objects in the array in my inspector if possible so I could tweak the stats within unity. I've looked at scriptableObjects and different things but I am having a hard time putting it all together in an array from within unity. System.Serializable public class playerClass public string playerName public int lvl public int maxHealth public int health public int maxEnergy public int energy public int exp public class playerScript MonoBehaviour public playerClass player This is how I created an object for the player, I want to do something similar for the enemies but put them in an array so I could randomly pick from them. If there is a better way to do this I'd also welcome some advice ) thank you |
0 | Trouble GamePad input on iOS but works perfect on Android I am having trouble getting input from on iOS devices (iPhone 6 Plus and iPad). Here is my code, if (Input.GetKey (KeyCode.JoystickButton14)) A chr show "A" if (Input.GetKey (KeyCode.JoystickButton13)) B chr show "B" ........................................... if (Input.GetKey (KeyCode.JoystickButton11)) Select chr show "SELECT" And in OnGUI() GUI.Label (new Rect(0,0,100,100), "Pressed Button " chr show, guiStyle) Code works perfect on Android device. I also have tried following if (Input.GetButton ("JSButton")) JSButton chr show "JS Button 14" Please Help Me! |
0 | How can I toggle between single shots when clicking the mouse left button and automatic none stop shooting when clicking the mouse right button? I'm talking in build not in editor ! using System using System.Collections using System.Collections.Generic using UnityEngine public class Shooting MonoBehaviour SerializeField private Transform firePoints SerializeField private Rigidbody projectilePrefab SerializeField private float launchForce 700f SerializeField private Animator anim SerializeField private bool automaticFire false SerializeField private bool slowDownEffect false private void Start() anim.SetBool("Shooting", true) public void Update() if (isAnimationStatePlaying(anim, 0, "AIMING") true) if (Input.GetButtonDown("Fire1") automaticFire false ) automaticFire false if (anim.GetBool("Shooting") true) anim.Play("SHOOTING") LaunchProjectile() else if ( automaticFire true amp amp Input.GetButtonDown("Fire2")) automaticFire true if(automaticFire true) anim.Play("SHOOTING") LaunchProjectile() private void LaunchProjectile() foreach (var firePoint in firePoints) Rigidbody projectileInstance Instantiate( projectilePrefab, firePoint.position, firePoint.rotation) projectileInstance.AddForce(new Vector3(0, 0, 1) launchForce) projectileInstance.gameObject.AddComponent lt BulletDestruction gt ().Init() bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName)) return true else return false I tried to do it in the Update using the automaticFire variable but it's not working fine. When clicking first the left mouse button it's shooting singles but then when clicking the mouse right button it's shooting automatic but then when clicking the left mouse button again it's not back to single shots again it's staying on automatic. The idea is right click mouse button automatic fire left button each time clicking the left mouse button the automatic should stop and then single shots with the left mouse button. And this way to toggle between the Fire1 and Fire2. Fire1 left mouse button click Fire2 right mouse button. |
0 | Unity update sizeDelta in OnValidate based on Layout Group computed values I'm trying to update the sizeDelta of a RectTransform in OnValidate. I'm trying to grab the computed values from a Layout Group. Here's what I've got if UNITY EDITOR void OnValidate() UnityEditor.EditorApplication.delayCall Resize private void Resize() if (this null) return RectTransform parentRect (RectTransform)gameObject.transform RectTransform textRect (RectTransform)tabText.transform textRect.sizeDelta new Vector2(parentRect.rect.height, parentRect.rect.width) layoutElement.preferredHeight parentRect.rect.height endif At first this seemed to be working, but it only works the first time OnValidate runs. Subsequence invocations of Resize() sets the sizeDelta to Vector2(0, 0). I'm wondering what causes this and if there's a way to avoid it. If I remove the delayCall, the values are correct, but I get warnings SendMessage cannot be called during Awake, CheckConsistency, or OnValidate I'd like to do this at edit time since there's no need to compute this stuff at runtime. |
0 | Oculus Rift DK1 and DK2 compatability issues For a project I need to make a multiplayer game using Unity and the Oculus Rift. My project works fine with the DK2 but it turns out the second rift is a DK1 and it won t work with Unity. I was thinking the best way forward would be to use an older version of the Oculus Runtime and Unity. Does anyone know what versions of Unity and the Runtime I need to have both the DK1 and DK2 work with Unity? |
0 | OnDrag does not work, but OnMouseDown works There is a code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.EventSystems public class DragAndDropGame MonoBehaviour, IBeginDragHandler, IDragHandler Camera MainCamera void Awake() MainCamera Camera.allCameras 0 Debug.Log(MainCamera) public void OnBeginDrag(PointerEventData eventData) Debug.Log("OnBeginDrag") public void OnDrag(PointerEventData eventData) Vector3 newPos MainCamera.ScreenToWorldPoint(eventData.position) newPos.z 0 transform.position newPos void OnMouseDown() Debug.Log("OnMouseDown") OnMouseDown fulfills, but the implementation ofIBeginDragHandler, IDragHandler not. What can be wrong? |
0 | Why does this raycast code give me a NullReferenceException? The Error in the code is NullReferenceException Object reference not set to an instance of an object for if (hitxx.collider.tag "soldier") Please help! Thanks in advance void Update () Physics.Raycast (eyeenemy.transform.position, (eyeenemyfront.transform.position eyeenemy.transform.position) 20,out hitxx) Debug.DrawRay (eyeenemy.transform.position, (eyeenemyfront.transform.position eyeenemy.transform.position) 20,Color.green) if (hitxx.collider.tag "soldier") gameObject.transform.LookAt (soldier.transform.position) Debug.Log ("chuchu") |
0 | Why does Unity save textures in bitmap format for APKs and IPAs? Why does Unity save graphic resources in Android apks and iOS ipas in a bitmap format(width height bpp)? I want to save my resources in a small apk, but instead of 1mb for an image Unity stores 11mb for a single image. |
0 | How do I hide an Input field? I have in my hierarchy tab a Canvas. Inside the canvas I have an Input Field that holds a placeholder and a text. I read the documentations and didn't find how to hide the Input field. I want that if a if statement is true, then it will show the input field. Else you won't see it. How can I implement it? EDIT I thought about an idea to test If I press the O key on the keyboard it disappears, and if I press again it appears and so on. This is what I tried bool shown true Use this for initialization void Start () Update is called once per frame void Update () GameObject inputField GameObject.Find("InputField") if (Input.GetKeyDown (KeyCode.O)) shown !shown inputField.SetActive (shown) I play the scene and when I press the O key I get NullReferenceException Object reference not set to an instance of an object If I double click on the console message it highlights me the if (Input.GetKeyDown (KeyCode.O)) line. Something not good does the SetActive(bool) method, I suppose. |
0 | How to attach an UI button to a prefab and follow it in Unity2D My plan is creating a button above my prefab (a tree) and whenever my character is detected, the button will appear and allow me to click on it to active a dialog. I just want my trees are randomly spawned and stay still so it's not "follow" actually but I would like to know in that case too. I did some researches but most of them were about Text and HP MP things, which weren't used by UI system. One more thing, I kinda new to code so it would be fantastic if I got a full code (Button follow only). Thanks in advanced. |
0 | How to find and modify specific entity or gameobject in Hybrid ECS? I am rotating 3 cubes in Unity with Hybrid ECS and the code goes like this public class RoatateECS MonoBehaviour public float moveSpeed 10f class RotateSystem ComponentSystem struct RoadComponets public Transform transform public RoatateECS rotateECS protected override void OnUpdate() foreach(var e in GetEntities lt RoadComponets gt ()) e.transform.Rotate(0f, e.rotateECS.moveSpeed, 0f) Inside OnUpdate all three cubes are rotating, I want to rotate the second cube in the opposite direction but how would I find a specific cube and modify it ? |
0 | how to put elements around circle with equal distance? I know circle formula and know how to draw it. but I want put 4 points on it with equal distance from each other. how can I do that? I work with unity. |
0 | How can I unify the collision handling of melee spell attacks in a networked environment? I am trying to figure a good way to create the battle system of a game. The game is fast paced and the gameplay needs to be precise (think hack n slash) What I would like to achieve is a simple and unified system that could manage any type of attacks, that could be tweaked. My first idea is to use physics shape For example an arrow will just be a little capsule moving forward, an explosion would be a growing sphere collider, and melee combat could be done by spawning a box in front of the player. One problem I have with this is that I'd like to have an authoritative server for multiplayer, which means I shouldn't use too much actual physics. So, is there any standard way people program these sort of systems, do you know any good starting point better than just using physics? |
0 | Do I have to use new keyword for unity single game object? I'm using Unity4. Do I have to use new keyword for single game object? look at the following code. 1. GameObject obj new GameObject() obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject 2. GameObject obj obj Resources.Load("Prefabs Ball", typeof(GameObject)) as GameObject is it the same? |
0 | How to Fetch a Frame Number from Animation Clip I'm trying to find out how to fetch the frame number from an animation clip accurately. I don't want to get a value between 0 and 1 that shows as a percentage as a decimal how much of the animation has played (example 0.5 the 5th frame of 10 frames) because it doesn't seem to be accurate. This also seems impractical, so is there a way to accurately fetch a frame number from an animation clip? Thanks. |
0 | Should I use Coroutines to change variables in inspector smoothly? I want to change the aperture of the depth of field in the camera smoothly by using Mathf.SmoothDamp and a Coroutine, however, since I'm new to game development, I don't know if this is the right way to do it. Any suggestions? Code using System.Collections using UnityEngine using UnityEngine.UI using UnityStandardAssets.ImageEffects public class GameStartController MonoBehaviour public Button startButton public GameObject cubeSpawner Use this for initialization private void Start() startButton startButton.GetComponent lt Button gt () public void StartGame() EnableCubeSpawner() SpawnStartingCubes() HideStartMenu() StartCoroutine("FocusCamera") PlayBackgroundMusic() Enables the cube spawner, so it can start spawning cubes private void EnableCubeSpawner() cubeSpawner.SetActive(true) private void SpawnStartingCubes() cubeSpawner.GetComponent lt CubeSpawner gt ().GenerateStartingCubes() private void PlayBackgroundMusic() var audio GameObject.FindWithTag("Audio").GetComponent lt AudioController gt () audio.PlayBackgroundMusic() private void HideStartMenu() startButton.transform.parent.GetComponent lt CanvasGroup gt ().interactable false startButton.transform.parent.GetComponent lt CanvasGroup gt ().alpha 0f private IEnumerator FocusCamera() var camera GameObject.FindWithTag("MainCamera").GetComponent lt Camera gt () var velocity 0f while (Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture) gt 0.001f) Debug.Log(Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture)) camera.GetComponent lt DepthOfField gt ().aperture Mathf.SmoothDamp(camera.GetComponent lt DepthOfField gt ().aperture, 0f, ref velocity, 0.3f) yield return null camera.GetComponent lt DepthOfField gt ().aperture 0f |
0 | Admob is load failing by No Fill error I m using official admin plugin for Unity implementing Reward video. But it s only working for test unit id, when I replacing it to my own unit id, it just failing load by error No Fill . Even when I add test device, still happening the issue. How can I fix this? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.