_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Random environment runtime generation in Unity I need a tip for a project basically I need to randomly generate an environment (a map) for a game. As generating a full map completely procedural is impossible for me, I thought to create a static map (I made one ice based, one rock based, one desert based etc) with some static elements in it like a "spawn area", a map border. Next, I made some "piece of map" smaller that the actual size of the border (like the border is 1000x1000 and this piece are max 200x200). Each piece has the same style of the border (e.g. I made few icy pieces with a spawn of polar bear and few desert pieces with a spawn of scorpions). Now I'm stuck I can't randomly spawn all the little squares inside a border amp I can't randomly spawn them inside and make them match one with an other. Incidentally, this is a 3D project. |
0 | Unity Spin wheels to move vehicle I am just getting started with Unity and I'd like to ask a question. If I have a "Vehicle" object that has two children "FrontWheel" and "BackWheel" (both 'wheels' are cylinders), how should I set everything up such that I can move the entire vehicle by turning its wheels? When I apply a torque to "FrontWheel", the vehicle starts to move, but instead of the whole thing the moving together, the chassis is rolling on the cylinders and eventually falls off. How can I prevent it from doing that? |
0 | How can I make a custom editor that creates deletes game object clones around a given point I have been manually creating and deleting clones of my game objects that I arrange in a circle around a given point. Each of the objects is rotated making each object the same angle apart from the others as seen in the image below. My objects range from 2 to 10. Doing this manually is very cumbersome, especially when changes have to made. How can I create a unity custom editor that allows me to specify a number of game object clones I want to create around a specified anchor point? Additionally, adjusting the number of clones should dynamically create delete clones and reposition rerotate them. |
0 | 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? |
0 | Split the camera into sections? I have a layout for my game similar to this Where the light gray area is reserved for HUD elements and the dark gray area is reserved for the actual game. One function I want to offer in the dark gray area is the ability to zoom and move around, which works independently from the light gray area, meaning that no matter how far I zoom in out or how far I move, the light gray area remains unaffected. How can I do this without always taking the offset center into account? How can I completely separate the game play part and the HUD? |
0 | Can I use two Collision Boxes on the same GameObject? I have two Collision Boxes on the same GameObject. I don't want the Collision Boxes to be triggers. I want the Collision Boxes on the actual GameObject, not its children. For example, if I want to check for a headshot. My reason for not wanting triggers is that a trigger is already being used. My reason for not wanting children is for cleanliness. I understand there are work arounds. I was wondering if there was a more direct approach. When there is a collision, how can I check which Collision Box is hit? |
0 | How do i play mp3 files in Unity Standalone? I am making a game in Unity in which the player can select music files in their hard drive to use them in game. I use the WWW class to load the sound files, but this only works for OGG, WAV and Tracker files. I use the following code WWW www new WWW ("file " soundPath) while(!www.isDone) yield return 0 GetComponent lt AudioSource gt ().clip www.GetAudioClip(false, true) I want to play audio files in mp3 format, which is the most widely used format for music in general, but when i try to play them, this gets printed to the debug log Streaming of 'mp3' is not supported on this platform. How can i easily achieve mp3 playback on desktop? |
0 | Animating two characters (like a fighting game) whose animations are tied together? So, say one character grabs another and throws him against a wall. Are these two separate animations that get attached to each character? Or is this really one animation that somehow involves each character model to itself? I'm using the Unity game engine. |
0 | Tower Defence stat storing system I'm trying to find a smart way to store and retrieve stats for a tower defence game, but am currently unsure as to which approach would be best. Description The stats system should quite basic, there are 4 different towers, with up to 5 different levels each. One important requirement is that the stats should be stored in an XML file so that the game designer easily can access and balance the stats. (He knows nothing about programming) I can see two ways of doing this By creating a TowerStats class which hold values for one type of tower for one level. Something like public class TowerStats2 public TowerType type public int lvl public int damageLow public int damageHigh public float range public float attackFrequency Then i would load the stats from the XMl file using Linq and XDocument and load it directly into a TowerStat List. I would do this for each tower so in the end there would be 4 different List's which would hold the different level stats for the specified tower. gunTowerStats 0 would hold level 1 stats of the gun tower rocketTowerStats 2 would be level 3 stats of the rocket tower When a new tower is bought by the player or when a tower is upgraded, the stats would then be taken from the List so something like UpgradeTower() lvl towerStats gunTowerStats towerLevel 1 Alternativly I could hardcode all the values, and have one big class which would go something like this gunTowerDamageLvl1 4 gunTowerDamageLvl2 8 gunTowerDamageLvl3 15 rocketTowerDamageLvl1 10 you get the point. I know that hardcoding is never never really the way to go. But does that also count for this kind of example where all possible tower attributes are known and will not change? the only thing that will change are the values of these attributes. Question I'm personally in favour of the first way, but I must admit that I find both ways a bit clumsy, would it be alright to do it one of these ways or is there a much smarter and more obvious way to deal with this that I'm completely unable to see? I hope my question is understandable. |
0 | How can the board fit the screen perfectly in Unity's 2D Roguelike tutorial? I follow the tutorial 2D Roguelike tutorial. I want to understand how happen that 10x10 board of 32x32 sprites covers screen perfectly? Like what does this depend on? |
0 | Is there a method to add partial scorch marks or decals on top of existing sprites? Let's say what I have is a planet like so What I want to do is to add a scorch mark like this Now, if this was a one time thing, it wouldn't be a problem. I'd make a sprite for this specific occasion and move on. The problem is however, I want the scorch marks to look different and to not use all that much memory (because there might be too many of them on screen and this is for mobile). The scorch marks will almost always be the same size but the planets will be different sizes, so one sprite that is scaled is not what I want (it would look too big on bigger planets and too small on smaller ones). Also, I want to be able to rotate the sprite to make it look different. I've thought about adding another sprite on top of the planet (a border like hack) to hide this but there can be other planets that are really close by to this one and they would be hidden too. I've looked at a lot of stuff but nothing like this exists. I've managed to create some stuff with a stencil shader and the use of a sphere with zero Z scale. This does create the problem of showing the sprite on other planets and I haven't been able to push forward on this. This is what I can currently make This is what I need to make |
0 | Why does Resources.Load cause a CastException in this case? I am doing this string fontName "freespin big" TextAsset xml Resources.Load lt TextAsset gt (fontName) Texture2D image Resources.Load lt Texture2D gt (fontName) Font font Resources.Load lt Font gt (fontName) if (font null) font new Font() AssetDatabase.CreateAsset(font, "Assets Resources " fontName) In Resources, we have freespin big.png and freespin big.xml. I am planning to import the png and xml and create a font. So I check if the font object is there, if not create it. But I get this error if the font does not exist yet InvalidCastException Cannot cast from source type to destination type. If I try to do this Font font Resources.Load lt Font gt ("blorg") Where no files are named "blorg", I get null as I expect. Shouldn't Resources.Load return null if it finds no fonts with the right name? |
0 | Setting Camera's Viewing parameters manually I am working on Context aware camera in Unity. in this project i have to set parameters of the camera each frame manually depending on what camera sees on the screen. New View (v) direction is given and Up (u) and Right (r) vectors should be such that they minimize torsion with previous frame's u and r. I have deployed the following code to accomplish the given task Vector3 viewNew m Normal Vector3upNew Vector3.Cross(viewNew,m CameraPrevTransform.right).normalized Vector3 rightNew Vector3.Cross(viewNew, upNew).normalized ... transform.forward viewNew transform.up upNew transform.right rightNew The problem is it seems like Unity tries to automatically adjust parameters when one of the directions (up, forward, right ) are set. Is there a workaround ? is it possible to get more control of the camera? |
0 | Roatating a Game Object downward In my game I have a rocket which is traveling horizontally across the screen. What I am trying to do is when the player runs out of fuel, the rockets engine stops (already coded) and then the rocket will slowly rotate to point at an almost 45 degree angle and fall down off the screen as gravity takes its affect. How do I do this? |
0 | How to get an OnClick Event in Unity to action? I am new to Game Dev and I am following a Tutorial. Within this tutorial, we create a quest system, that allows you to accept or decline a quest. This tutorial is based on Unity 5 and I am using 2020.1 so there could be version differences that could be causing the issue. I have a script called Quest001Buttons.cs public class Quest001Buttons MonoBehaviour public GameObject ThePlayer public GameObject NoticeCam public GameObject UIQuest public GameObject ActiveQuestBox public GameObject Objective01 public GameObject Objective02 public GameObject Objective03 public void AcceptQuest() Debug.Log( quot Accept Registered quot ) ThePlayer.SetActive(true) NoticeCam.SetActive(false) UIQuest.SetActive(false) StartCoroutine(SetQuestUi()) IEnumerator SetQuestUi() ActiveQuestBox.GetComponent lt Text gt ().text quot My First Weapon quot Objective01.GetComponent lt Text gt ().text quot Reach the Clearing quot Objective02.GetComponent lt Text gt ().text quot Open Chest quot Objective03.GetComponent lt Text gt ().text quot Get Weapon quot QuestManager.ActiveQuestNumber 1 yield return new WaitForSeconds(0.5f) ActiveQuestBox.SetActive(true) yield return new WaitForSeconds(1) Objective01.SetActive(true) yield return new WaitForSeconds(0.5f) Objective02.SetActive(true) yield return new WaitForSeconds(0.5f) Objective03.SetActive(true) yield return new WaitForSeconds(9) ActiveQuestBox.SetActive(false) Objective01.SetActive(false) Objective02.SetActive(false) Objective03.SetActive(false) I have an Empty GameObject called quot QuestButtonManager quot which I have assigned the above script to. I also have a UI GamObject called quot Accept quot and I have attached the QuestButtonManager GameObject to the OnClick() Event within that component. I have selected quot Runtime Only quot and the function of quot Quest001Buttons.AcceptQuest quot . When I run the game and press the Accept Button...the game seems to not function after that and is stuck on that screen, with the button highlighted...not even the Debug.Log text is printed in the console. Any help is greatly appreciated before I give it up and look for a more updated version to learn on. |
0 | How do I not let my explosion go through the walls like bomberman? I have this problem that I want to fix. Every time I place a bomb it goes pass through the wall even if I added a Layermask to tell if it's a wall or not. public LayerMask levelMask public GameObject explosion void Start() Invoke("Explode", 1f) void Explode() Instantiate(explosion, transform.position, Quaternion.identity) StartCoroutine(CreateExplosions(Vector2.up)) StartCoroutine(CreateExplosions(Vector2.down)) StartCoroutine(CreateExplosions(Vector2.right)) StartCoroutine(CreateExplosions(Vector2.left)) GetComponent lt SpriteRenderer gt ().enabled false Destroy(gameObject, .3f) private IEnumerator CreateExplosions(Vector3 direction) for (int i 1 i lt 3 i ) RaycastHit hit Physics.Raycast(transform.position new Vector3(0,.5f,0), direction, out hit, i, levelMask) if (!hit.collider) Instantiate(explosionPrefab, transform.position (i direction), explosionPrefab.transform.rotation) else break yield return new WaitForSeconds(.05f) |
0 | Color change effect, with a sharp line separating the old new colors I want to achieve some sort of "transformation" effect in Unity while changing colors in a mesh. For instance, when changing its color from red to blue, I have a line going around the mesh, where the part of the mesh on one side of the line is red and the other is blue. Over time, the line moves so the object is entirely blue. From what I understand, I would need some sort of custom shader to do that? Or would I need some sort of animation? I really have no clue how to achieve this kind of effect so any tips are welcome. |
0 | Difference between a normal function and coroutine without yeilding anything I just came across a coroutine in my project, which does few calculation, which could have been done using normal function.There is no loop in that coroutine and contains yield return null in the last line. Is there any specific reason to use coroutine rather than normal function? void Init() RenderObject() IEnumerator Init() RenderObject() yield return null EDIT Inside the RenderObject function, they are calling another coroutine which has two yield instructions yield return true and yield return new WaitUntil(() gt based on certain condition, calling to server takes place primarily. |
0 | stop the camera clipping objects I'm using RTS camera as it is the player in my scene, how can I stop the camera clipping into buildings? |
0 | How to convert point coordinate when taking a snapshot? Can anyone explain me please how to convert point from Screen coordinate system to Texture 2D? The screen size say for example 700x500 and Texture2D must be of size 1024x768. I am getting points from scene, convert them with camera.WorldToScreen and then multiply by ratio, which doesn't work correctly for some reason. Here is my code PROCESSING POINTS cam pts i detector.WorldToScreenPoint(pts i ) cam pts i .y Screen.height cam pts i .y cam pts i .x cam pts i .x (ImageWidth (float)Screen.width) cam pts i .y cam pts i .y (ImageHeight (float)Screen.height) SAVING CAPTURE SCREEN RenderTexture rt new RenderTexture(ImageWidth, ImageHeight, 24) detector.targetTexture rt Texture2D screenShot new Texture2D(ImageWidth, ImageHeight, TextureFormat.RGB24, false) detector.Render() RenderTexture.active rt screenShot.ReadPixels(new Rect(0, 0, ImageWidth, ImageHeight), 0, 0) detector.targetTexture null RenderTexture.active null Destroy(rt) byte bytes screenShot.EncodeToPNG() string filename string.Format("Screenshot 0 .png", counter) System.IO.File.WriteAllBytes(filename, bytes) The red points must be at the corners of the pallet. I am new in Unity and C and will be thankful if someone explains me how to do it right. |
0 | Unity 3D engine for Ubuntu? Is there any way to get Unity 3D to run on Ubuntu. I am currently running Ubuntu 12.04 64bit edition. I also have Wine installed. |
0 | FPS using mouse to move rather than keys Hi I am developing a First person game but would like to use the mouse to move on a click to move as opposed to the keys. I also need to disable Y movement and restrict the x movement to 180. What ever values I enter into the input manager, it seems to be ignoring them as I still have both x and y when I run the game. I dabbled with the standard unity FPS but is seems very jagged on movement and from what I can see being a new user, their doesn't seem to be a way to restrict y movement. Can someone help with this or suggest a good tutorial on this type of movement. Thanks |
0 | How to get x in radius percentage value? How to find the percentage value from A to B when I know the X value in between these two points? I created this picture to kind of illustrate what I mean better. I wrote this function which gets the percentage, but how do I also include the center offset? private float GetPercentage(Vector2 point, float radiusOffset, float centerOffset) float radius Math.Min(circle.rect.width 2f, circle.rect.height 2f) radius radiusOffset return 1f (Math.Max(Math.Abs(point.x), Math.Abs(point.y)) radius) The radius offset is from 0 1, 0 being the 0,0 position and 1 full radius. The center offset is from 1 0, 1 being the 0,0 position and 0 being the radius border. |
0 | How do I make spring animation for a 2D game? I want to create a realistic spring object, as a sprite, that compresses and expands when a force is applied and released, respectively. The only thing I know is that it requires some complex animation, but have no idea how to do it. I'm using the Unity engine, but otherwise, it is a general question. |
0 | How Lots of ComputeBuffers at Once Affect Performance Unity How will lots ComputeBuffer instances affect performance? And why? I know that I should call ComputeBuffer.Release() on every ComputeBuffer I create, but will it affect performance if I were to have lots of open ComputeBuffers at once? and by "lots" I mean hundreds to thousands. It of course goes without saying that all of those ComputeBuffers will be released at some point, possibly at the same time. |
0 | How to free up TEXCOORD slots for Unity's Universal Render Pipeline? I am writing custom a custom shader for Unity's Universal Render Pipeline (Version 7.3.1). The meshes are built using three separate UVMaps for different portions of the mesh. The reason I actually need all three to be separate is because two of them are scaled amp offset independently by a C script, kind of like texture atlas. I need the front and back of a sphere to be independently textured using this. I followed this tutorial from CyanGameDev to get an understanding of the new syntax for URP as I had previously done this with the Built In RP. The older version still used the Vertex amp Fragment functions to draw it, but it was unlit so I was free to use as many TEXCOORDs as I needed. Now as I followed this tutorial, I found that I needed all 8 available TEXCOORDs immediately just to get it functioning struct Varyings AKA v2f, or OUTPUT from Vertex function to Fragment function float4 positionCS SV POSITION Position in ClipSpace AKA screen space float4 color COLOR float2 uv TEXCOORD0 DECLARE LIGHTMAP OR SH(lightmapUV, vertexSH, 1) the 3rd argument is the TEXCOORD index ifdef REQUIRES WORLD SPACE POS INTERPOLATOR float3 positionWS TEXCOORD2 endif float3 normalWS TEXCOORD3 Normal in WorldSpace as defined in Vert function ifdef NORMALMAP float4 tangentWS TEXCOORD4 Tangent in WorldSpace as defined in Vert Function endif float3 viewDirWS TEXCOORD5 Convert to half3 for just vertex lighting, free up a TEXCOORD? half4 fogFactorAndVertexLight TEXCOORD6 x fogFactor, yzw vertex light ifdef REQUIRES VERTEX SHADOW COORD INTERPOLATOR float4 shadowCoord TEXCOORD7 endif Is there anyway I can remove some of these and still get PBR ish result? For instance, I don't necessarily need the fog on this object. As well, I do not really want to perform this in Shader Graph if I can avoid it. One thought I am having is to declare the uv as a float4 and just swizzle the texcoord like uv.xy for UV1 and uv.zw for UV2 but my understanding is the texturing and offset is stored within the Z amp W vectors which is why you used to define a MainTex ST float4. EDIT The specific effect is this The background is one texture (not a solid color, or i'd do this differently) And the Foreground is another texture (Alpha channel symbols) Through the script, you control which background section or foreground symbol you want by changing the tiling of the texture. The idea is that you can have many different combinations of the two textures. The back of the sphere will always have just the background color. The script is such that the amount of tiles on a texture does not have to be square, and the foreground and background textures do not need the same amount of tiles (its calculated at start). At any given time, only one of the tiles is shown on the sphere, mapped to both sides. The final look is explained in a previous question of mine The final look is explained in a previous question of mine |
0 | HDR bloom techniques using post processing in Unity3D I've seen many posts on how to accomplish HDR bloom effects in Unity3D using its (now legacy) Bloom component as part of the standard assets package. I'm trying to replicate it using the new post processing package, but I can't seem to get it to work. I have an an emissive material that's emitting at a value far 1 sitting at 10 Bloom is set in a Post Processing Profile, and the threshold is 1 Finally, HDR is enabled on my camera, along with a deferred rendering path. Yet this doesn't work. I only see the bloom effect if I set my bloom threshold lt 1, after which all my materials bloom. It's as if HDR is not actually enabled. Anyone know why? |
0 | Unity3D Android Move your character to a specific x position I want to move my character (which is a cube for now) to a specific x location (on top of a flying floor ground thingy) but I've been having some troubles with it. I've been using this script var jumpSpeed float 3.5 var distToGround float function Start() get the distance to ground distToGround collider.bounds.extents.y function IsGrounded() boolean return Physics.Raycast(transform.position, Vector3.up, distToGround 0.1) function Update () Move the object to the right relative to the camera 1 unit second. transform.Translate(Vector3.forward Time.deltaTime) if (Input.anyKeyDown amp amp IsGrounded()) rigidbody.velocity.x jumpSpeed And this is the result (which is not what I want) https www.youtube.com watch?v Fj8B6eI4dbE Does anyone have any idea how to do this? I'm using UnityScript (Javascript). |
0 | Trapping Asserts in Visual Studio I'm writing a 2D game with some fairly complex off screen logic, with plenty of room for bugs. My usual habit is to write code with a lot of Asserts in it. When an Assert gets hit I drop into the debugger, have a look around, find and fix the bug. Works for me. Problem is how to get Unity Asserts to call into the Visual Studio debugger. So far they just seem to get generate a log message in the Editor Console, and then Unity carries right on as if they didn't matter. What use is that? There is an 'experimental' option in the Unity VS settings, but it doesn't seem to do anything (good or bad). Any suggestions? I can think of a couple of really hackish things to try, but surely there must be a right way? After further experimentation Enabling Assert.raiseExceptions (only) makes Unity grind to a halt (instead of carrying on regardless) but otherwise no change. No trap into VS. Enabling the experimental Exceptions mode (only) causes Unity to crash with a bug check on the first assert failure. Doing 1 2 is the same as 1 only. This is VS 2015 in case it matters. |
0 | Should I include 3rd party libraries in my Plugin? I'm using Firebase services in a custom plugin that will be released later, Should I include all 3rd party libraries like Firebase on the final plugin package or is there another way to handle this in unity ? |
0 | How move camera where i look? I am try make simple flying camera. Without character. But than I press forward camera moving to another direction. void Update() horizontalInput Input.GetAxisRaw("Horizontal") verticalInput Input.GetAxisRaw("Vertical") var mouseX Input.GetAxis("Mouse X") var mouseY Input.GetAxis("Mouse Y") var trm Camera.main.transform if (horizontalInput ! 0 verticalInput ! 0) trm.position moveSpeed new Vector3(horizontalInput, 0, verticalInput) var rotateValue new Vector3(mouseY 2, mouseX 2, 0) trm.eulerAngles rotateValue trm.rotation Quaternion.Euler(rotateValue) Than I press 'W' camera moving to left... I understand that it is necessary to coordinate the motion vectors and camera rotation. How best to do it? |
0 | How to Make Saving System Serializable Hello I ve been working on a save load system for my RPG inventory, and I was wondering whether there was a way to make the script use Serialization instead of PlayerPrefs, because I want the player to be able to access their save file. The main issue I run into with this code is how it mixes up the same variable in different itemHolders, causing duplication. Also, I heard that PlayerPrefs is better used for settings or preferences. Here s my script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using System using System.Runtime.Serialization.Formatters.Binary using System.IO public class ItemInformation MonoBehaviour These are the assets for the item to change public Text nameText public Text descriptionText public Text regenText public Text amountText This is the identifier for each item public string identifier These are the variables that change with the different items public string itemName public string itemDescription public float itemRegeneration public int itemAmount Starts on awake void Awake() Function to change the object's information and such nameText.text itemName descriptionText.text itemDescription regenText.text quot HEALS quot itemRegeneration quot HP quot Loads game data LoadDataIfNeeded() void Update() amountText.text quot HAVE quot itemAmount private void SaveData() string jsonString JsonUtility.ToJson(this) PlayerPrefs.SetString(identifier, jsonString) Creates file to store variables BinaryFormatter bf new BinaryFormatter() FileStream file File.Create(Application.persistentDataPath quot InvData.dat quot ) SaveData data new SaveData() Gets the player data data.itemSave myItemAmount.itemAmount Writes player data to file and encrypts it bf.Serialize(file, data) file.Close() public void LoadDataIfNeeded() if (PlayerPrefs.HasKey(identifier)) string jsonInstance PlayerPrefs.GetString(identifier) JsonUtility.FromJsonOverwrite(jsonInstance, this) Extracts the data from the binary file and reads it BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath quot InvData.dat quot , FileMode.Open) SaveData data (SaveData)bf.Deserialize(file) file.Close() myItemAmount.itemAmount data.itemSave else SaveData() Holds data that is to be saved Serializable class SaveData Variables for save file public int itemSave |
0 | How can I add to the text multiple words or numbers? Now I'm using 0 I add anywhere in the text in the editor 0 and it will add the random number or random word. But I want now to be able to add for example also 1 and 2 so if for example the array of words is hello,hi,bye and I will make in the editor in the text 0 1 it will add randomly two words from the array like hello and hi or hi and bye. It will pick up two random words. I don't place the 0 and 1 in same place each one in other place in the text and each time it will pick two random words and will display one word at 0 and one at 1 Same for the numbers. using System using System.Collections using System.Collections.Generic using System.Text using UnityEngine using UnityEngine.UI public class CustomText MonoBehaviour public Text textField public Vector2 randomRangeHours public string words public bool randomWords false private string defaultValue private string originalValue public void Init() defaultValue textField.text originalValue textField.text GenerateRandomHour() private void Update() if (Input.GetKeyDown(KeyCode.Space)) GenerateRandomHour() private void GenerateRandomHour() string word "" if (words.Length gt 0) word words UnityEngine.Random.Range(1, words.Length) string numberName UnityEngine.Random.Range((int)randomRangeHours.x, (int)randomRangeHours.y).ToString() int t Int32.Parse(numberName) if (t 1) defaultValue defaultValue.Replace("hours", "hour") else defaultValue originalValue if (randomWords) textField.text string.Format(defaultValue, word) else textField.text string.Format(defaultValue, numberName) |
0 | How can I implement a short cut grass effect? I've been looking at some screenshots from games like Rocket League and FIFA and I started wondering one would achieve the short cut grass effect. Is it a shader? Is it actual geometry? Or just textured quads? If anyone could point me in a direction, that would be greatly appreciated. |
0 | How should I load change activate scenes? Scenes are confusing the hell out of me and I'm pretty sure they should be simple to understand. When the game loads, only the current scene has a buildIndex ! 1. In order give it a 'real' build index I need to load it by path or name (because there's no build index). The scenes are ten game scenes, one title scene and one persistent scene (which has the player and the status bar with the score etc.). Should I load a scene every time I change scene and then load additive afterwards or should I be using Set Active Scene? All the scenes are ticked in the Build Settings. I'm looking at the index with this private void Start() var sceneName "Persistent" var sceneBeforeLoading SceneManager.GetSceneByName(sceneName) Debug.Log( "Scene sceneBeforeLoading.name , BI sceneBeforeLoading.buildIndex ") SceneManager.LoadScene(sceneName) var sceneAfterLoading SceneManager.GetSceneByName(sceneName) Debug.Log( "Scene sceneAfterLoading.name , BI sceneBeforeLoading.buildIndex ") Which outputs Scene , BI 1 UnityEngine.Debug Log(Object) Title Start() (at Assets Scripts Title.cs 10) Scene Persistent, BI 1 UnityEngine.Debug Log(Object) Title Start() (at Assets Scripts Title.cs 13) |
0 | Wandering motion in Unity I am trying to come up with a smooth wandering motion for my game object using Unity. What I currently doing is rotate the object by some random angle calculated every 1.5 second delay. But I am aiming getting a smooth rotation whenever it transitions to a different randomly generated angle. Below is my script attached to my character. void Update () if (canWander amp amp (currTime delay lt Time.time)) changeAngle() currTime Time.time if(canWander) Wander() private void changeAngle() float prevPosY transform.position.y Vector3 waypoint Random.insideUnitSphere new Vector3(10,prevPosY,10) waypoints are generated based on random unit sphere ( bounds of the plane they are on ) Vector3 relative transform.InverseTransformPoint (waypoint) float angle Mathf.Atan2 (relative.x, relative.z) Mathf.Rad2Deg transform.Rotate (0, angle, 0) private void Wander() transform.position transform.forward Time.deltaTime acceleration if (acceleration lt maxSpeed) acceleration 0.5f So the character wanders with newly generated random angles every time but its not a smooth transition. It suddenly transitions to the new angle and it does not feel realistic at all. What could I possibly change with my current code to make it more smooth and realistic? |
0 | What i'm missing in this multiplayer Unity photon code? i'm having some troubles in my first, simple, multiplayer racing game, using Photon and Unity. Following classic photon tutorial i've written the code below, but, it won't work properly. In particular there are any smooth movement and "other" player car continue to appear and disapper... maybe i could post a video. void Update() if (gsAppSettings.gameType Enumerators.GameType.MultiPlayer) if (pv.isMine) pv is PhotonView GetPlayerInput () WeaponsManagement () else SyncMovement () else if (gsAppSettings.gameType Enumerators.GameType.SinglePlayer) GetPlayerInput () WeaponsManagement () void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.isWriting) if (photonView.isMine) stream.SendNext (transform.position) stream.SendNext (transform.rotation) stream.SendNext (rb.velocity) else correctPlayerPos (Vector3)stream.ReceiveNext() correctPlayerRot (Quaternion)stream.ReceiveNext() currentVelocity (Vector3)stream.ReceiveNext() updateTime Time.time private void SyncMovement() Vector3 projectedPosition this.correctPlayerPos currentVelocity (Time.time updateTime) transform.position Vector3.Lerp (transform.position, projectedPosition, Time.deltaTime 4) transform.rotation Quaternion.Lerp (transform.rotation, this.correctPlayerRot, Time.deltaTime 4) EDIT This is video. As you can see, the low car is "flipping" up and down https www.youtube.com watch?v QKpYl7C5rl0 amp feature youtu.be |
0 | In Depth Lockstep Explanation I'm making a multiplayer game built upon a lockstep system and I'd just like a better grasp on the concept. My main question is on how to get every command to simulate at the same time on every client, or rather, on the same points in each client's timeline. I'm using a fixed update of 10 frames per second for simulating every object's position from movement commands (Click and move style) the same way. How do I tell all clients to execute all commands at the same relative time to the first command? Note I'm using Unity3D and a sufficiently accurate physics implementation. I just need to get across every command at the correct time. |
0 | Unity equivalent of glDepthMask or alternative I'm trying to achieve the following setup 2 cubes. In the image attached they are the green and pink cube. They are both rendered culling their front faces, so that they are visible if a camera stands inside of them. The 2 cubes intersect, as show in the image. The pink cube has an opening (door, window, portal, whathaveyou) thru which a camea facing in the direction of the opening, can see the green cube. Here is the interesting part if the camera is not looking thru the opening however, I want the green cube face on the right side of the image to not be visible. The culling is easy just say Cull Front in a surface shader. The part that I'm not sure how to pull of in Unity is the last point. The way I would solve this in OpenGL, in a forward rendering pipeline, would be by turning on depth testing glEnable(GL DEPTH TEST) and, when rendering the green box, I'd disable depth writing to the z buffer but keep testing on. i.e. glDepthMask(GL FALSE) then render the cube and then re enable writes to the z buffer. Essentially treating the green cube as if it were a skybox. But I have not found anywhere in the ShaderLab documentation an equivalent of glDepthMask. there is ZWrite and ZTest but these just are equivalent to glEnable(GL DEPTH TEST) and glDepthFunc, not to the mask. Any thoughts? Alternatively, I was thinking of using clipping planes . In GL this would be using gl ClipDistance in the shaders. I would render the green cube with a clipping distance equal to the intersection point of both cubes 1, so it chops off that face. And the render the other cube without the clipping plane. But this would require updating the shader each time the clipping plane (intersection between the cubes) changes. UPDATE I actually think that ShaderLab's ZWrite lt On Off gt is the equivalent of glDepthMask. The issue is that I don't seem to be able to control rendering the green cube after Unity's skybox. If I were, the approach I'd take would be Unity renders it's skybox. I render my green cube with ZWrite Off. This implies z testing takes place against the fragments of the cube, but the buffer won't be updated with the z values of the cube after this pass. Render the rest of the geometry as usual. Since step 2 did not write to the z buffer, the geometry should cover everything as it normally does with respect to the engine's skybox. This means it would cover the green cube too. But, if the geometry (pink cube) had any openings, the pink cube would not write to the z buffer since there is nothing there. The buffer in those areas should be 1 (the default for infinitely away). I tried the above, which just meant creating a new surface shader with ZWrite Off and a tag "Queue" "Background 1", hoping it would mean "render after the skybox". But while it does prevent the green cube rendering on top of the pink cube, it also makes Unity's skybox render on top of the green cube. So not sure how to tell it to render after the skybox. |
0 | What's the best way to draw gizmos in build I currently use Unity gizmos for many debugging purposes, but I'd like almost all of them to be visible to the player in game (when the game is built). For example, when a player is dragging to place a wall along a grid, I use Gizmos.DrawCube. I know of a couple of options ALINE an asset on Unity asset store, but currently doesn't work with 2D Experimental URP Line renderer seems very manual and tedious to do, and I'm unsure how I could modify it using code Placing pictures as UI elements over selected tiles (seems pretty expensive to do?) Any suggestions are appreciated! |
0 | How to properly scale Image components to screen percentages? Let's take a Sprite. I have two methods for retrieving an orthographic size of the screen public static float Width() Camera cam Camera.main float height 2f cam.orthographicSize float width height cam.aspect return width public static float Height() Camera cam Camera.main float height 2f cam.orthographicSize return height Now, for the Sprite, I have an extension method public static void ScreenPercentWidth(this SpriteRenderer renderer, float percent) renderer.transform.localScale new Vector3( Screen.Width() 100f percent renderer.sprite.bounds.size.x, renderer.transform.localScale.y, renderer.transform.localScale.z ) Which I can use like sprite.ScreenPercentWidth(50f) and it works. What about a RectTransform Image? Is there any way that I could create similar methods, so I can scale the Image like in the above example? |
0 | If I want to create a top down 2D game should I rotate the camera? Do I have to rotate the camera to top down view if I want to crate a top down 2D game or just disable gravity? |
0 | Animating object, setting isKinematic false, and then letting physics take over I'm trying to create a "tree felling" effect, where the tree trunk falls over after being cut down by the player. I've used one prefab which contains my tree stump and tree trunk as children. In its default state, my tree trunk as a rigidbody with isKinematic true. When the player cuts down the tree, I begin an animation on the trunk which "tips it over". On the last frame, it sets isKinematic false at this point it should "fall over" because physicals gravity is in control and the center of mass is definitely over its base. However, the animation seems to be preventing it, like it's still "controlling" the transform. Adding a transition from the "fell" state to an "exit" state just resets the position rotation. Setting the animator to "animate physics" kind of works, but the tree just flies away, probably colliding with the stump or something. Disabling the animator after the animation kind of works, but this also causes the tree to go flying with some crazy physics. When left alone, OnCollisionEnter is called on the tree for colliding with my ground, yet the gameobject appears to still be stuck at 45 degrees and never touched the ground. It seems like the rigibody collider is not where the mesh transform is? Animating the object and then turning off isKinematic should work, it's been recommended to me on reddit and is the accepted answer on this question, so I'm not sure what could be wrong. Edit I can ease the physics problems by telling the trunk to ignore it's own stump (Physics.IgnoreCollision(Trunk.transform, Stump.transform) ), but the base of the tree still "jumps" away from the stump, rather than "continue tipping over". I'm not sure what else could be at play. |
0 | Unintended window opening when pressing Unity's "Submit" button I've been working on a top down 2D game for a while now, and yesterday I found a strange bug that I just can't explain to myself whatsoever. I have a loot window for looting enemies, as well as a character panel to equip gear see stats. I realized that after I open and close a loot window, if I press the space button (used for attacking, not for opening any windows) while holding A LeftArrow or W UpArrow it opens the character panel. Once this happens, I can press space to open close the character panel. Went to the character panels OpenClose() function (all it does is set the canvas group alpha to 0 and block raycast to false and vice versa) which is being called unintentionally, put a debug.log inside to verify if it really was being called, and yes, it is. I look up all references to see where I used it, but I only use it in a single place in the project that is behind an if statement looking for they keycode C (NOT space). I added a debug.log for the Input.inputstring to see if somehow a magic C button press is ending up in that function, but no. If I press C to open the window, the debug log pops up, if I press space, the inputstring appears to be empty, so the if statement to get to the only place in the code referencing that function cannot be met. Removed the space button from my Player entirely, the behaviour still persists. Added another debug.log with stackTrace.GetFrame(1).GetMethod().Name to show who is actually running this function, but it turns out that if I run it and press C, it says it's being opened by the update function in the UIManager (as expected). If I run it the strange, unintended way, it says it is being run by the EventSystems Invoke function. Coupled with the fact that the behaviour persists despite the space button being removed from the player, I realized that it's Unity's built in "Submit" button being pressed. Strange behaviour It appears to call the submit function on the OpenClose button for the character panel, but only under the circumstance that I closed a loot window and haven't clicked the mouse anywhere yet afterwards. If I deactivate the button that holds the character panels OpenClose function, the behaviour stops. The button shouldn't be pressed though, because it is on a canvas group with alpha 0 block raycast false, just like all the other buttons with the identical function that work fine. The loot window has no idea about the character panel either, and all the windows are properly wired to their own OpenClose function. Upon further inspection, the window only starts showing up if, after closing a loot window, i press A LeftArrow Space or W UpArrow Space. This is getting more and more confusing for me. So basically my issue is how do I figure out why this function is being called? It feels as if closing the loot window somehow "caches" the OpenClose button for the character panel onto the submit button, but only until I click elsewhere on the screen. Did you guys have any experience with a similar situation? Could you share some pointers on how to debug this? What is the "submit" button usually used for, and what would make it only work in combination with the left top directional buttons? I've spent about 4 hours on this now and don't know how to get any further. |
0 | Unity How to keep sprites sharp and crisp, even while rotating How can I maintain crisp, sharp edges on sprites, while avoiding the aliasing caused by rotation? None of the things I've tried produce a pixel perfect non rotated block, while allowing rotation without aliasing Click here for the sample project, which also has some extra images in it. Click here for my Unity Forums Thread Ideally, this is what it would look like From Photoshop, not Unity. Flawless edges, smooth corners, and very faint aliasing when rotated. Screenshot from Github project Row 1 Non rotated Perfect edges, pixelated corners Rotated Pixelated everywhere Row 2 Non rotated Perfect edges, smooth corners. Rotated Pixelated edges, smooth corners Row 3 Non rotated Blurry everywhere. Rotated Blurry everywhere Row 4 Non rotated Not quite perfect edges, pixelated corners Rotated Blurry everywhere Row 5 (MY BEST SOLUTION SO FAR) Non rotated Semi blurry everywhere. Rotated Semi blurry everywhere Texture for "no border padding" texture Texture for "with padding" texture Shader Method (Note I'm a total shader newbie) I created a fragment shader to draw the block. It has AA (via smoothstep) built in, and throttles it on as block is rotated (so that there is no AA when it's not rotated) This has some problems A (geometry) shader doesn't seem like the correct solution for this problem at all, since I'd have to make a shader for all the geometry that has this problem. But maybe there is a shader that can apply AA to a texture, that doesn't do anything for vertical or horizontal (non rotated) edges? Corners of block with AA turned off are pixelated This doesn't seem too difficult to fix I'd probably want it to work identically to row 2 (non rotated) Not sure how much AA to apply (when rotated) so that it's as sharp as possible for a given screen DPI. I thought this is what mip maps were good for, since the highest possible res texture should be chosen. (Another reason why a texture based solution seems best) Other things I've tried Vector graphics (per Unity's vector package) Unity's vector package required 4x MSAA to look right, which was too intensive for mobile devices MSAA Creates blurry graphics (is there a way around this?) |
0 | How to make lens flare ignore layers work with first person character in Unity 5? I have a simple lens flare on my directional light (sun) and I would like the flare to only be visible when the sun is directly visible, naturally...But right now with the default ignore layers, the flare is only visible when 'Everything' is ticked. Obviously this therefore means you can see the flare through other objects which I don't want. I first thought that the camera must have been sitting 'inside' the standard assets first person character's collider, but it was definitely outside the collider so I don't see why it won't show...Could someone show me how to fix this? Thanks. |
0 | How to create a correct Unity package copy, which will not be replaced when you import? I create a "Package 1" consisting of section A (unique) section B (which will be repeated in all my other packages). This package works correctly is he is alone. Next, I create a "Package 2" consisting of section C (unique) Section B (from Package 1). To save time, I replaced the texture maps in the materials belong to old section A parts and replace this part on section C (directly on models in the Mesh.) I renamed most objects in the scene and in the package as a whole. I delete all prefabs of section A and create prefabs section C , because they are not pick up name changes. The prefabs of section B , I left as is. Now when I import Package 2 in the scene that already contains the Package 1 , it begins the mess Package 1 Files are replaced by Package 2 , even them are named differently. How to avoid it? I can t create each scene from scratch, unfortunately it will lead to the insane time consuming. Huge thanks for your support! |
0 | How can I make a gameObject jump quick at first then start slowing down after a while? How can I make a gameObject jump quick at first then start slowing down after a while? It definitely has something to do with deltaTime. |
0 | Coins don't show up in game in Unity I have a 2D game I'm making with Unity, and I want the player to be able to collect coins that I place all over the game. I used the coin prefab with a 2D circle collider and an animation to make it spin. The problem is that only the first coin I put into the scene shows up in the game, and when I collect that one coin, the counter shows that all the others have been collected as well. Here's the script I attached to the player for the coins private uint tokens 0 void OnGUI() GUILayout.Label ("Tokens " tokens) void CollectToken(Collider2D tokenCollider) tokens Destroy (tokenCollider.gameObject) void OnTriggerEnter2D(Collider2D col) if (col.gameObject.CompareTag ("token")) CollectToken(col) This is my current setup for the object properties Thank you for any help! |
0 | Assigning valid moves on board game I am making a board game in unity 4.3 2d similar to checkers. I have added an empty object to all the points where player can move and added a box collider to each empty object.I attached a click to move script to each player token. Now I want to assign valid moves. e.g. as shown in picture... Players can only move on vertex of each square.Player can only move to adjacent vertex.Thus it can only move from red spot to yellow and cannot move to blue spot.There is another condition which is if there is the token of another player at the yellow spot then the player cannot move to that spot. Instead it will have to go from red to green spot. How can I find the valid moves of the player by scripting. I have another problem with click to move. When I click all the objects move to that position.But I only want to move a single token. So what can i add to script to select a specific object and then click to move the specific object.Here is my script for click to move. var obj Transform private var hitPoint Vector3 private var move boolean false private var startTime float var speed 1 function Update () if(Input.GetKeyDown(KeyCode.Mouse0)) var hit RaycastHit no point storing this really var ray Camera.main.ScreenPointToRay (Input.mousePosition) if (Physics.Raycast (ray, hit, 10000)) hitPoint hit.point move true startTime Time.time if(move) obj.position Vector3.Lerp(obj.position, hitPoint, Time.deltaTime speed) if(obj.position hitPoint) move false |
0 | How to play an animation backwards in Unity? I know this question has been asked before but it all involves using the Animation(?) component, so that is no longer any good in Unity 5.3.1f1, I explain a bit more later. I'm trying to simply get an animation to play backwards. On the object that I want to have an animation play backwards on, I have an animator. private Animator anim ... anim GetComponent lt Animator gt () If I do animator.speed 1.0f It tells me Animator.speed can only be negative when Animator recorder is enabled. Animator.recorderMode ! AnimatorRecorderMode.Offline So I try putting on an Animation component on the game object, and making the clip the animation. Every time I do anything with the Animation component in script, it tells me the component must be marked as Legacy. That is no good, because when I tried making it Legacy it caused multiple problems including not being recognized by the Animator. Also GetRef errors. The entire Animation component seems like it's treated as legacy now or is just broken. So I decided well maybe I could just try to get the animation to play backwards in the animator and having the animator record it, and then using that backwards recorded animation in the actual game. I cannot figure out how to this, even if I click record in the Animation view anim.recorderMode ! AnimatorRecorderMode.Record. I don't know what to do. All I want to do is play the same animation backwards without having to copy and paste an animation in the Project and moving all of the keys around so that they are reversed. Please help. Unity's animation system seems so convoluted in script. |
0 | Unity Set quad to angle of floor mesh I have a cursor object (simple quad) that I'm moving around above a floor mesh. The floor mesh has varying heights (hills and such). How can I set my quad to sit at the same angle as the mesh floor? I'm using a raycast to cast down on the position of the cursor and get the angle of the floor mesh using hit.normal, then reflect. RaycastHit hit var rayStart new Vector3(transform.position.x, transform.position.y 5f, transform.position.z) if (Physics.Raycast(rayStart, Vector3.down, out hit, 10f)) if (hit.collider.tag quot Floor quot ) Vector3 incomingVec hit.point rayStart Vector3 reflectVec Vector3.Reflect(incomingVec, hit.normal) cursorSprite.transform.eulerAngles reflectVec (I've left out the position code, that works, its just the angle code that doesnt) I've tried a bunch of variations, altering the reflectVec angle x, y and z but I can't figure out how to get it correct |
0 | Changing transform of ParticleSystem makes it not play? Unity 2018.2.9f1, only 1 script, there is no other code. The scene is very simple (I just started). I'm working on a mobile game and I'm trying to play a particle effect at the tap location. I managed to get the particle effect to play, but when I attempt to change transform.position the particle no longer displays at all. I see the TapEffect's GameObject X and Y coordinates being updated in the Editor, but the actual animation is not playing. This is the script I have attached to my player, the particle is the only child of Player at the moment. public class Player MonoBehaviour private ParticleSystem tapEffectParticle private Vector2 touchPos void Start () this.tapEffectParticle transform.GetChild(0).GetComponent lt ParticleSystem gt () void Update () if(Input.touchCount gt 0) Touch touch Input.GetTouch(0) if(touch.phase TouchPhase.Began) touchPos touch.position tapEffectParticle.transform.position touchPos tapEffectParticle.Play() Here is a screenshot of the TapEffect Particle, default particle. This is a view of the Player GameObject selected. |
0 | How to achieve light effect on a car panel icons? I'm making a car and I want to make lightable icons on its panel. I want to add 'on' and 'off' effect to them separately. The Sprites are plane objects, with one material and UV texture for each plane. If I change material property it will change in all objects which use this material. I don't think creating 10 materials for 10 sprites is the best choice, what should I do in this situation? |
0 | Unity How to keep the music muted on reloading the scene? I am giving the user a UI button to mute and unmute the ingame sounds but the problem is when I mute the sounds and then when the game ends and the game scene reloads the sounds comes back up which is really annoying. After some searching I came to know that I need to use DontDestroyOnLoad(transform.gameobject) but it makes the copy of the whole thing and now I have two copies of the same music. Also I don't know if this is the only way or not but just to mute unmute an audio source it feels kind of overkill to me since I have a many components attached to my gameobject and then just to mute unmute it copies the whole thing. Can someone tell me how to fix that duplicating problem and also is there any simpler way to achieve this? |
0 | Unity Inspector Turn off script for a group? I have a large group of objects in Unity that can be grouped and for one instance I want to turn off a script on each one, for over 100 this can be tedious, can this be done group wise within the inspector? Instead of me going into each one and manually turning a script off? I have tried doing this within a script but it will not work for this situation. |
0 | Unity3d iOS build where are the textures? First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing. Everything is just a solid block of whatever color I made it. When running in Unity I see everything correctly. See images below. To complicate things I'm using custom shaders, and all the objects are custom procedural meshes. Quads that I build in script. If I switch the paper backplate shader to a built in shader I still only see white on the iPhone. So I suspect that somehow the textures just aren't making it to the iOS project. When I look in the iOS project I can't find any textures. Where would they be in the iOS project? For example in Xcode under Build Phases Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons. Surely I'm missing something simple. I tried renaming the folder where I keep my textures to "Textures". Also my textures are not built in to the shader but added programmatically like this void Awake () meshFilterComponent GetComponent lt MeshFilter gt () Material material GetComponent lt MeshRenderer gt ().material material.SetTexture(0, paperTexture) material.color new Vector4(1f, 1f, 1f, 1f) Where paperTexture is set up in the GameObject to point to the correct texture. Is there any way to force a texture to be part of a build? Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed? Running On iPhone Running In Unity3D |
0 | How to use MaterialPropertyBlocks to randomly change the color of multiple materials on an object? I have a character prefab for a civilian with 5 materials. Each one should be a random color but I don't want a new material for every civilian in the game. I asked a question earlier and had a good answer. However I was pointed towards this question with MaterialPropertyBlocks. This is the code I currently have void Start () Color newShirtColor shirtColor Random.Range(0, shirtColor.Length) MaterialPropertyBlock props new MaterialPropertyBlock() props.AddColor(" Color", newShirtColor) GetComponent lt SkinnedMeshRenderer gt ().SetPropertyBlock(props) It works really well but the color is assigned to the whole mesh. How can I do this for each of the 5 materials on the object so that it only changed the color for the assigned parts of the mesh, with only one material for each section? |
0 | How do I scale my spell target indicator to match the radius of OverlapSphere I have a spell system in which some spells have an Area of Effect. To get the targets I use Physics.OverlapSphere. I show the player an indication of the spell's radius by spawning a Unity plane primitive at the target position and scaling it to match the radius of the spell. How would I scale my spell target indicator visual to correctly match the radius of OverlapSphere? I have tried setting the scale of the plane's X,Y,Z to radius 2, but this does not seem to align with the overlap sphere radius. data.indicatorInstance.transform.DOScale(data.parent.radius 2, 0.5f) And just for completeness sake, below is the OverlapSphere call. Physics.OverlapSphere(targetPosition, data.parent.radius) |
0 | How do you partition a level and create screen transitions out of these partitions? The levels in Castlevania games, you walk forward and then come to a point on the level where the screen stops scrolling but is not a deadend and there's no door either. They just wanted to transition to the next room for some reason (like a hallway transitioning to another room). I want to create something like this in Unity, using 2.5d (3d characters constrained in 2d plane) question is, do I separate each transition to a scene? But that seems kinda wasteful (I don't know, maybe). Or just one scene and develop the level as a whole and do some camera programming for the transition making sure everything lines up? |
0 | Good way to establish an inventory system? Fairly new to Unity as a whole, and while making a prototype game I came across the issue of setting up an inventory system. So far, I've been stuck on what sort of structure it should have, given Each quot Mob quot (player, enemy, NPC, etc.) has its own inventory Objects can have children attached, which should be saved (e.g. Gun gt Attachment Manager gt Magazine Rail etc.) Simpler items (ammunition, etc.) are stackable An inventory has quot pouches quot which are available only for certain objects (magazines, health items, etc.) and have a certain volume At first, I simply made a Mob gt Inventory Manager gt Pouch gt Item system where everything was a child of its respective parent, but obviously even with colliders sprites disabled that's possibly hundreds of transforms per mob being shifted around each update. Right now, I'm just parenting each mob's inventory system to a static quot Inventories quot object to get past the issue of that many transforms, but is there a better long term solution that takes into account saving loading and scene transitions? Right now, I'm considering Turning each item with children (guns with attachments) into a prefab and saving it (not ideal) Using an ID system to instantiate objects on load by loading the root object (gun), then the children (attachments) given certain parameters (but the variables, like the rounds loaded into a magazine, would be tricky to load) Having different prefabs for items depending on whether or not they're equipped, on the ground, or in an inventory, and switching between them as needed |
0 | Unity3D WWW get HTML displayed in browser I currently have in a web page, on a localhost server, some information that I want to use in Unity. My problem is that this information are stored in some js variables. I tried to use the WWW class in a coroutine, but I only get the html source code. Is there a way to get the value of this variables inside Unity Editor ? Thanks ! |
0 | Puzzled about game mods I'm new to game development. I was thinking of different ways to create a game. I discovered Unity3d as much preferred indie game engine and yet so powerful. Then I read about game mods, which I found pretty exciting too. So, I now have two questions. Are Mod creation Software SDKs developed by the same company which made the original game? Are there any custom made (recent) mod sdk? Is it even possible to make one like that? Is it possible to port a model from one mod sdk (say, Halflife) to another mod sdk (say, Skyrim)? |
0 | Unity Interrupting Animations When I interrupt an Animator Controller during an Animation and reopen it the Armature gets stuck (more or less) at the point where the previous Animation was interrupted. How can I safely and instantly quit an animation without destroying it? Please watch the Video to fully comprehend the problem https youtu.be O9X5SBATHRw Screenshot of Problem Screenshot of Animator Controller Part of the Weapon Switch Script disableWeaponModel(weaponNameList activeWeapon ) Disable active Weapon Model if (holsteredWeapon 1) If player carries only 1 weapon holsteredWeapon activeWeapon Active Weapon is holstered else Player already carries 2 weapons actionDropGun() Active Weapon is thrown (New LOD generated) activeWeapon getWeaponIDfromLOD(targetName) Active Weapon is set to Target LOD setWeaponVars(activeWeapon) Set all variables to the active Weapon setWeaponModel(weaponNameList activeWeapon ) Set Weapon Model to the active Weapon setAnimator(weaponNameList activeWeapon ) Set Animations to the active Weapon setAnimator(string name) Function from above (last code line) void setAnimator(string name) Add new guns here if (name "MP5A3") currentWeaponAnimation MP5A3 Animation else if (name "Rpk 74") currentWeaponAnimation Rpk74 Animation else if (name "Skorpion") currentWeaponAnimation Skorpion Animation Variables from setAnimator(string name) |
0 | How can I reference the frontmost part of a mesh in my Unity code? (and help making FPS projectiles seem more real) I have started making a PC game using Unity. It's just a test project, where I'm making as basic as possible FPS shooter. I'm using the FPS Controller prefab, and I have also a rifle model attached to it. The result is pretty much what I wanted. Now I'm considering how I want to create projectiles for the gunfire. I think it will be best for me to create each bullet as just being a ray from the gun barrel heading forwards, OR I might create rigidbodies from the gun barrel I'm not sure yet. My question is What is the proper way to reference the point in space in which the gun barrel current ends? At the moment, I am thinking just attach ANOTHER gameObject to the gun model, and just manually position it where the barrel finishes. But this seems 'cheaty' and I think perhaps there is a better way (something like mesh.position.z mesh.length, but I can't seem to find anything like mesh.length). I haven't posted code at all, because I haven't really written any on this project yet. I would also be very interested to hear the pro tip version of how best to simulate this gunfire (ie. is it best to use rigidbodies? or somehow use raycast or something? or some better way that I haven't even dreamt of) |
0 | Built in Terrain analogs search is it worth to use imported 3d model? I think 3d model is better than the built in terrain component in Unity when it comes to optimization. But when it comes to texturing terrain made in 3rd party 3d modeller, how to apply resulting texture in Unity? If the terrain is too big you can't bake it in UV map. Otherway you should split it in many UV's and each one is separate material, which kills performance in the game. Other decision that i see is to use generated type of material and just tile it across the terrain mesh, but you can't draw the details like roads on it... So i'm confused is it really worth it to use Unity's terrain analogs or there is no way to do so efficiently? |
0 | Make gameObject stick to another gameObject after it has collided with it? Currently, I am using the following code to make objects stick to other gameObjects. rb GetComponent lt Rigidbody gt () rb.isKinematic true gameObject.transform.SetParent (col.gameObject.transform) It works perfectly, but it causes many other problems... For example, after colliding, it can no longer detect collisions... Is there an alternative to this code (which makes a gameObject stick to another one after collision)? |
0 | Mythbuster Mirror Operation with Quaternion Mirror operation all vertex positions must be reflected by a specific plane (here YZ).Synonyms FlipHorizontal, SymmetryX, MirrorX, What implementations I already know that work 1) Multiplying by 1 scale. Unfortunately that is not allowed in unity because it messes with physics and lighting. 2) Vertex Manipulation. Yes, it works!!! And now here comes the "Myth" from mr. evil person... Mirror operation can be implemented if you get a "lucky" quaternion rotation. He says that a) if "euler rotation" suffers from Gimbal Lock, and Quaternion doesnt. b) Then If quaternion (Matrix 4x4) cannot represent mirror operation, then increasing the dimensions to Pentaternion (Matrix 5x5), Or Hexaternion (Matrix 6x6) is sure to solve the problem. Note I am not looking for "Reverse" operation (15 degree rotation converted to (360 15) degree rotation at that axis). I am looking for a way to "free" my model from those rotation limiting axes... I tried everything but couldn't achieve "Red" projection with a quaternion, maybe I miss something... Is he right ? Or a quaternion cannot implement reflection and that myth is Busted? Unity allows me to use all transform operations (Translation, Rotation, Instancing) but not scaling (messes up physics and lighting). |
0 | 2D jerky motion with AddForce and physics I have a problem smoothly motion I see jerking when I am using physics and AddForce. It's not a question related to Update or Time.deltaTime I created simple scene with few lines and sphere. When player clicked " " button, I apply force to sphere, but motion is jerky and is not smoothly (please see web version below). Project fixed ortho camera, sphere with disable gravity, few cubs and bouncy as default material. To fixed this problem, I tried to use some solutions from posts, related with jerking motion in Unity http answers.unity3d.com questions 10907 smoothing rigidbody movement over a bumpy track.html answers.unity3d.com questions 228095 why is the motion jerky in a simple 2d game.html answers.unity3d.com questions 275016 updatefixedupdate motion stutter not another novic.html Things, that I tried Interpolate for sphere rigibody slightly better, but jerky is still here. Change Vsync(Dont Sync, Every Blank, Every Second Blacnk) and Quality (Fastest Fantastic) nothing Use different object for collission (just rigibody and collision object) and display object(mesh renderer). This InterpolateToTarget.cs script in source folder nothing. In previous other game (with gravity, other default material, etc.) I used motion forward without AddForce, but I faced with jerky motion, too. I tried all solutions, that I find (FixedUpdate Update with deltaTime, Coroutine, Transform.Translate, Interpolation, Lerp, LateUpdate...) and I saw that only one combination (small AddForce Interpolation and Simply Quality setttings (VSync is turn off)) give me acceptable smoothly motion. But in this game I need AddForce with larger value and this solution is not work in this case. Web version https dl.dropbox.com u 15321992 2DjerkyMotion.rar Sources https dl.dropbox.com u 15321992 2DjerkyMotion.rar Android apk dl.dropbox.com u 15321992 2dJerkyMotion.apk Code that I am using for motion public class TestMovingScript MonoBehaviour private Rect restartBtnRect new Rect(20, 20, 120, 60) private Rect rightMoveBtnRect new Rect(Screen.width 100, Screen.height 100, 100, 100) private GameObject player private Vector3 movingVector new Vector3(1, 0, 0) Use this for initialization void Start () player GameObject.FindGameObjectWithTag("Player") player.rigidbody.AddForce( movingVector 20) Update is called once per frame void Update () private void OnGUI() if (GUI.RepeatButton(restartBtnRect, "Restart")) Application.LoadLevel(0) if (GUI.RepeatButton(rightMoveBtnRect, " gt ")) player.rigidbody.AddForce( movingVector 20) I suppose in web version this jerking is not as noticeable, but on Android it is a horrible. Also, try to play in web version few minutes and you will see it. I don't believe, that Unity3d does not allow to build smoothly Android game, so maybe I missing something in physics player setting. I will be grateful for any suggestions and ideas. Thanks, Dmitry. |
0 | Getting notified about a change of a public variable in a script I have a script attached to a GameObject. In this script I have the variable public int Rotation If this value is changed, I need to do some calculations. I know that I can be notified when this value is changed in the Inspector (for example if somebody enters a different number), but I would like to be notified if this value is changed by another script. Is that possible, or do I need do introduce a void ChangeRotation(int uNewValue) or similiar? Thank you! |
0 | Is it possible that elements in the StreamingAssets folder are not read in build? I'm making a 2D game. In my StreamingAssets folder I have a JSON file with some info about inventory items (id, description, rarity, name, is stackable or not) and a png file which contains a pixel map (128x32) of the level I want to load after a first scene (this is from Quill18's tutorial https www.youtube.com watch?v 5RzziXSwSsg , basically a specific color corresponds to a specific prefab. An object reads through all the pixels and then spawns the level). The fact is that I have issues with both these elements when the game is built (everything works perfectly in the game window in Unity) the inventory items don't collide with the player and the level is not loaded. This is the code that gets the image name public string levelFileName string filePath Application.dataPath " StreamingAssets " levelFileName byte bytes System.IO.File.ReadAllBytes (filePath) Texture2D levelMap new Texture2D (2, 2) levelMap.LoadImage (bytes) And the pickable objects basically have a collision detection script and have a specific ID, so that when they collide with the player, the inventory adds in a free slot an image with the specs correspondant to that ID (i.e. ID 1 then it's an health potion, is stackable, it's not rare and so on). Everything else works fine in the game. Do you think that the issue is linked to the StreamingAssets folder (first time using it) or is it just a coincidence? And also could you help me solve the problem? Thank you in advance for any kind of help. Edit my Player logs |
0 | what happens when you set transform.position in Unity? Unity has both transform.positionandtransform.localPosition. When I do transform.position.x 3f does unity automatically update transform.localposition? and vice versa? Why can I not see this when I go to the definition of transform.position in VS? |
0 | How to fix pink tiles when there is a problem with the Shader? Because of some dumb mistake I did fifth time, I had to repaint my level in my 2D game. The problem is that the tiles I use from the Tile Palette turn into pink because of some shader error. I came to this conclusion after a long time of browsing through the forums. I am 100 sure that this will happen again, because I don't know what causes this behavior. So, prevention is not an option for me. What is the solution? By DMGregory's suggestion, I was able to recreate this dumb behavior of mine in an empty project. What I do is dragging and dropping a tileset onto a tile palette which I am using, and then overwriting the current tile palette. Then, the former assets are lost (I guess?) leaving me with pink tiles. Attached picture is one of my levels created using Tile Palette. How do I take this back? I don't want to repaint my level everytime I do whatever that causes this behavior. |
0 | How to navigate through google Map in unity I am working on loading the google map and navigating through the map. I have loaded the google map which shows the current location in unity. Now I need to show the direction from Place A to Place B.How Can I implement this in unity |
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 | Should Unity lifecycle methods be annotated with the UsedImplicitly attribute? Does annotating Unity lifecycle methods with the UsedImplicitly attribute improve the readability of your code? For example public class Example MonoBehaviour UsedImplicitly private void Awake() DoSomething() private void DoSomething() ... This blog post on "Structuring Your Unity MonoBehaviours" suggests this approach as a useful convention. Annotate any Unity lifecycle methods (Start, Awake, Update, OnDestroy etc.), event methods, and other functions that are implicitly (or automatically) invoked in your code with the UsedImplicitly attribute. This attribute, although included in the UnityEngine.dll, is used by ReSharper to disable code cleanup suggestions for methods that are seemingly unreferenced. It also helps to make the code easier to read for people who are newer to Unity and your codebase, especially for events that are referenced via the inspector. (Note I don't think ReSharper shows code cleanup suggestions for seemingly unreferenced Unity lifecycle methods, so that might be outdated advice.) I agree with the above post that it could be helpful for those newer to Unity. I also think it could be useful to label those Unity lifecycle functions that are not used as frequently as Awake, Start, and Update. But I am wondering if this is actually a good convention for "clean code", or if it's just noise that reduces readability. |
0 | Unity launches both Visual Studio and Monodevelop simultaneously When I open a script for editing from Unity, both Visual Studio and Monodevelop are launched, resulting in two instances of the same solution to be open in two different script editors. I am presently running the latest version of Unity 5.50fs (though I also experienced this issue in the previous build prior to installing Unity's latest update), in conjunction with Visual Studio Community Edition 2015, and Visual Studio Tools For Unity 2.3.0. I also have my external script editor set to VS in the preferences window of Unity. While investigating this issue I came across a forum thread of someone experiencing a similar problem, where MD opens instead of VS. This seemed to be a result of a hard coded reference to MD for redundancy in cases where VS might fail to load, which I thought sounds like a plausible explanation for my situation as well. The general consensus was that when VS takes a little too long to open, Unity reverts to MD under the assumption that their is a problem with VS. This explanation seems even more likely in my case because this issue only occurs when I first open Unity for the day if I have had VS open recently MD does not open, and VS opens quite quickly, likely a result of being cached in my computers memory. The work around offered to avoid MD launching instead of VS in that thread, was to change the name of the MD executable, so that Unity would be unable to launch MD, giving VS time to finish loading. I was however hoping to find a better solution. I like the fact that Unity has that redundancy in place and would rather keep it intact, and I don't know why but changing the executable solely for that purpose makes me feel a little OCD. Other ideas I have tried include reinstalling Unity, running both Unity and VS as an administrator, and launching VS prior to opening the script in Unity (in this case Unity opens a second instance of VS). Has anybody else experienced both script editors being launched simultaneously and or have any other ideas on how to resolve it? It's obviously not a critical issue or anything, but it is a bit annoying. |
0 | How can I send different contoller input to the different player avatars? My apologies in advance for the vague question, since I don't understand the problem well enough to ask in finer detail. I want to create a multi player Unity application using the Oculus SDK. Let's say there are two players in the scene, A and B. The problem is this When player A presses a button using his index finger, the hand avatar for player B also displays a moving index finger. In short, hand movements for one player are also observed for the other. Controller inputs are also read without any ability to distinguish whether they originate from player A or B. What are the possible approaches for eliminating this problem, if it is mandatory that I continue using Oculus SDK? |
0 | Simulate wind in a powder game I would like to create a game similar to powder game. I've got a 2d array that stores different types of powder such as sand, water, gas, and fire. I've managed to get these to all move around successfully. I would now like the powders to react to wind. For example if there is fire it should push air upwards. If the air is moving upwards it will move other bits of powder around. The way I've been trying is to have two more 2d byte arrays. One for the wind x direction and another for the wind y direction. The fire will then add an amount to the cells and each update will add the wind x and y to the piece of powder that is on that cell. This almost works but pushes the powder much to fast. The difficulty in doing this is that the powder is on a grid while the wind could be going a variety of directions. What is the most efficient way of doing this? |
0 | How can I easily create edit a level for a scrolling shooter game? I've been asking this question over the years many a time, but I still haven't found an answer when i search for one. Now I have slightly more knowledge of how programming is done and want to start making some full games. I want to start with a side scrolling shooter (space style like R Type Gradius). I have many ideas in my head for good levels, and i even have some basic 3d skills in Maya Blender to make the assets, but I do not know how best to formulate the levels. Lets say the space shooter has 30 levels. Each level might have about 10 15 enemy types and a boss on some levels. How best to store the location of all the enemies? (Same scenario for all the background objects,obstacles, powerup locations etc.) Is there a better way than manually building the whole level in a Unity Scene editor view? Another way I have tried is to set spawn positions for every single object as a Vector2 or similar in XML or JSON, but how i did it that seemed even harder to make the levels than just inside the editor (not even accounting for having to write the functionality to get the data from the textfile). |
0 | How to use rigid bodies for characters? First off, I am making a game similar to SSB, which relies heavily on physics, even though it is a sidescroller. I am currently using Unity. In Unity there are quot character controllers quot which are used for characters that move, but they don't interact with other physics objects. There are also rigid bodies, which are completely realistic physics components. I can't figure out how to use rigid bodies for human humanoid characters. Here's some questions I have How should I move the character? Applying forces is not the way to do it, right? Would you set velocities or pixel by pixel movement, perhaps? What kind of collider should I use? I've been using a capsule collider. But is that the best way? How do you make him not fall down!? After some experimenting, I discovered that the character falls over (from applying force velocity and from the capsule collider tipping it over). Would you constrain the rotation in the Z axis? What do you do when he gets hit? If you've ever played SSBB you'll be familiar with this topic. I'm thinking that applying a force would be best in this condition? If you did constrain the rotation, would you un constrain it? |
0 | unity Rigidbody jump I absolutely don't know what is the problem with this code and I have tried everything without any success. I need help. void FixedUpdate() if (Physics.Raycast(transform.localPosition new Vector3(0f,0.1f,0f), transform.up,0.2f) ) grounded true else grounded false if (Input.GetButtonDown ("Jump") amp amp grounded) rb.velocity Vector3.up jumpSpeed Some time it jumps and some time it doesn't jump with no visible pattern. |
0 | Unity C Raycasts, How to Ignore Triggers? Let's say I have a Raycast, but I don't want it to collide with any triggers. I don't want to change the Project settings since that's a little inflexible. How can I have a Raycast ignore any triggers? |
0 | Calculating price increases in a virtual economy I'm trying to design a method to have price increase depending on the number of items bought from shops in my game. I'm fairly new to coding and I am struggling to figure out how to program the increase in price when buying multiple items. Currently the price increase is a percentage increase based on the quantity of items in store, however if I buy 5 items, all 5 items will be charged the same. How can I get it so each item is charged at a different price? I also need a reasonable inflation system, right now my code just determines a price increase based on the percentage of items remaining, but it's very simple and easy to exploit. It looks like this 30 2 28 1 (28 30) 0.07 0.93 1 0.07 1.07 10 1.07 10.7 Rounded up Price 11 I'd like to make this more complex also. |
0 | CrossPlatformInput Prefabs Button handler to move? I am currently trying to put two buttons on my UI that move a character left and right if touched down (Held). I would like to use the cross platform input, and would like the buttons to change the value of the Horizontal axis as my "A" and "D" keys would... And my code for moving my character is as follows private void Update() isGrounded Physics2D.OverlapCircle(groundChecker.position, .15f, groundLayer) float move CrossPlatformInputManager.GetAxis("Horizontal") moveSpeed playerRB.velocity new Vector2(move, playerRB.velocity.y) |
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 | Why does the Unity manual add "Quaternion.identity" to an instantiated object? In Unity's documentation you can find an example usage of Instantiate https docs.unity3d.com ScriptReference Object.Instantiate.html using UnityEngine public class InstantiateExample MonoBehaviour public GameObject prefab void Start() for (int i 0 i lt 10 i ) Instantiate(prefab, new Vector3(i 2.0f, 0, 0), Quaternion.identity) Why do they add the "Quaternion.identity" instead of leaving it blank? Wouldn't the engine instantiate the object with the original object's rotation anyway? |
0 | How to create a tube 2D in unity I want to create a 2D tube in unity which I can cut, suture and drag it, My idea is to use a small image in form of fragments but how i can do it like the picture bellow EDIT What I did until now Firstly I tried to use Linerenderer but it didn't work for me because i couldn't cut it so tried to create a tube of cubes I used an empty object as parent whit childs of cubes as you can see on the picture bellow with this way it was easy to apply the cut script so I just remove the fixed joint between the cubes where i click and for the appearance of the tube I started by creating it as a direct line and I turned on the game then by dragging the tube i get the form bellow and i copy the position of each cube and set it on the instantiation of the childs GameObject intestines top GameObject.Find("intestine top") setPositions() on this method I instantiate an array of vector3 contains all the position i get fragments new GameObject fragmentNum Vector3 position Vector3.zero for (int i 0 i lt fragmentNum i ) fragments i Instantiate(fragmentPrefab, positionArray i , Quaternion.Euler(new Vector3(0.413f, 259.96f, 536.531f))) fragments i .transform.SetParent(transform) var joint fragments i .GetComponent lt FixedJoint gt () joint.connectedBody parent.GetComponent lt Rigidbody gt () parent fragments i the result of what i did NOTE other problem of my solution is sometimes all the gameobjects disperss due to collision I think That's happen after a while of dragging the tube I didn't find what exactly the problem but when I change the direction of the collider to the X axis its solve the problem by 85 and for the drag script i use AddForce and velocity rigid.AddForce((dest rigid.position) 200f) rigid.velocity 0.8f |
0 | How can I change a shader alpha color in script? How can I get access to the Main Color and change the alpha color ? How do I know what is the variable of the main color in the shader code ? If it's Main Color in the Inspector then this is the parameter I should get in the script "Main Color" ? |
0 | changing color of sprite not every frame So I have been trying making this game, which changes color of sprites in it. It should only happen when OnMouseDown(). but it is executing every frame and cannot go out of the couroutine. I want the color change to be slower. Please mark the colors should still change. Please Help, public class control MonoBehaviour public bool startstop false SpriteRenderer m SpriteRenderer private void Update() StartCoroutine("Changecolor", 3f) IEnumerator Changecolor() yield return new WaitForSeconds(3) if(startstop true) int random Random.Range(1, 4) if (random 1) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.blue else if(random 2) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.red else if(random 3) m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.green else m SpriteRenderer GetComponent lt SpriteRenderer gt () m SpriteRenderer.color Color.yellow private void OnMouseDown() startstop !startstop |
0 | How to get smoother transition between the surface normals rotation of player in Unity I kinda have a problem that my player is snapping onto the other surface while I wanna move a ramp up. I want to have it rotate smooth to the normals of the ramp. How can I change the code below to a smoother rotation function of the player? Code void NormalsOfGround() RAYCASTS THE NORMALS ON THE GROUND THAT THE PLAYER MOVES ALONG SURFACE Debug.DrawRay(rayCastNormal.transform.position, transform.up, Color.blue, 2.5f) Ray ray new Ray (transform.position, transform.up) RaycastHit hit if(Physics.Raycast(ray, out hit, 2.5f, GroundLayer) true) transform.rotation Quaternion.FromToRotation (transform.up, hit.normal) transform.rotation |
0 | NULL REFERENCE EXCEPTION Object reference not set to an instance of an object So I have 3 scripts first for my player movementscript second for my speed powerup speedscript third for my obstacle box script i I'm trying to get the component of box script in speed script, to get the function 'added' (which is in box script) into speed script but it keeps giving me nullreferenceexception error Here are those scripts public class box MonoBehaviour SerializeField GameObject effect public int damage 1 SerializeField float Speed 10f SerializeField GameObject audioexplosion void Update() transform.Translate(Vector2.left Speed Time.deltaTime) void OnTriggerEnter2D(Collider2D col) if(col.CompareTag("Player")) Instantiate(audioexplosion, transform.position, Quaternion.identity) Instantiate(effect, transform.position, Quaternion.identity) movment tmp col.GetComponent lt movment gt () tmp.health damage Destroy(gameObject) public void added(float spd) Speed spd And here is my speed script. public class speedscript MonoBehaviour SerializeField GameObject effect SerializeField GameObject speedaudio SerializeField public float speed public float add v 5 private float timeindue SerializeField public box io void Start() io GetComponent lt box gt () Debug.Log(io) void Update() transform.Translate(Vector2.left speed Time.deltaTime) void OnTriggerEnter2D(Collider2D sp) if (sp.CompareTag("Player")) Instantiate(speedaudio, transform.position, Quaternion.identity) Instantiate(effect, transform.position, Quaternion.identity) box io GetComponent lt box gt () Debug.Log(io) io.added(add v) Destroy(gameObject) |
0 | Unity Hide GameObject that is behind UI I have the following example How can I prevent the part of the sprite that is highlighted in red and is behind the UI from being displayed on the camera, but having the background image still showing? |
0 | Circular draggable UI element in Unity canvas I am trying to implement my own runtime color picker that's easy to use for touch interfaces. I want the hue slider to be a ring, along these lines, except the whole ring texture would rotate when dragged. I have scavenged enough code to get a raw image object rotating when dragged in a UI canvas in the manner I'm looking for private float baseAngle private Vector2 pos public void OnBeginDrag(PointerEventData eventData) pos transform.position pos eventData.pressPosition pos baseAngle Mathf.Atan2(pos.y, pos.x) Mathf.Rad2Deg baseAngle Mathf.Atan2(transform.right.y, transform.right.x) Mathf.Rad2Deg public void OnDrag(PointerEventData eventData) pos transform.position pos eventData.position pos float ang Mathf.Atan2(pos.y, pos.x) Mathf.Rad2Deg baseAngle transform.rotation Quaternion.AngleAxis(ang, Vector3.forward) Since it doesn't use colliders, how can I limit the draggable region to a circle within the square bounds of the texture? Even better, also limit it to a ring rather than a whole circle. Will I have to implement my own check based on some pure math or is there a built in way? thanks! |
0 | Respawn not working properly upon scene reload. Why is this? So I made a respawn function and what is supposed to happen is the script it supposed to load a saved checkpoint. However I need to reset the scene (and again this worked just fine last night which was odd...). Essentially the checkpoint waits for a player and then when the player enters the current checkpoint is written to a .txt file. Upon reload or death the scene is restarted, the .txt file is read and grabs the checkpoint. Everything works fine without Scene scene SceneManager.GetActiveScene() SceneManager.LoadScene(scene.name) Reload scene. but I need that in order to "refresh" the scene. CheckPoint Code using UnityEngine using System.Collections public class Checkpoint MonoBehaviour public LevelManager levelManager Empty level manager. Use this for initialization void Start() levelManager FindObjectOfType lt LevelManager gt () Unnneeded void OnTriggerEnter(Collider coll) if (coll.tag "Player") levelManager.currentCheckPoint gameObject lt DISABLE WHEN ES2 is fixed!!! Debug.Log("Activated Checkpoint " transform.position) ES2.Save(gameObject.name, "myFile.txt?tag checkpoint") Saves checkpoint to file. LevelManger Code using UnityEngine using System.Collections using UnityEngine.SceneManagement public class LevelManager MonoBehaviour Tooltip("Note this will also serve as the spawnpoint for the player!") public GameObject currentCheckPoint private GameObject player private int PHP public int RespawnHP Amount of health to give player upon respawn. void Awake () Use this for initialization void Start () player GameObject.FindGameObjectWithTag("Player") Update is called once per frame void Update () PHP GameObject.Find("InventoryManager").GetComponent lt InventoryManager gt ().PlayerHealth if (PHP lt 0) Debug.Log("Player HP has been depleted. Respawning.") RespawnPlayer() if (Input.GetKeyDown("r")) Debug.Log("Restarting level!") RespawnPlayer() public void RespawnPlayer() Scene scene SceneManager.GetActiveScene() SceneManager.LoadScene(scene.name) Reload scene. currentCheckPoint GameObject.Find(ES2.Load lt string gt ("myFile.txt?tag checkpoint")) Load saved checkpoint. Debug.Log("Player Respawning...") player.transform.position currentCheckPoint.transform.position GameObject.Find("InventoryManager").GetComponent lt InventoryManager gt ().PlayerHealth RespawnHP void RestartLevel() ToDo Restart level, and reload last check point. public static void SaveLevel() Saves the current level to file. ES2.Save(SceneManager.GetActiveScene().name, "myFile.txt?tag levelName") Saves level to file. ES2.Save("none", "myFile.txt?tag checkpoint") Overwrite checkpoint? Does anyone have a clue what is wrong? Like I said earlier the problem seems to arise on scene reloading. Response to comment(s) What behaviour are you observing at the moment? Jack Currently what happens is the player enters a checkpoint, the checkpoint is saved to a file, and upon respawn the checkpoint is loaded. After this I get spawned to the checkpoint that was saved but then immediately the level reloads itself and the player is not respawnd at the checkpoint. Here is a video to better demonstrate the issue (it will take a minute or two to finish up processing here as I've just pasted the link). |
0 | Creating paralax background in Unity3D I am trying to create some parallax background in Unity in 2D mode by tweaking offset of the background material and using tiling. I used this tutorial https www.youtube.com watch?v nGw UBJQPDY as a reference, but my material doesn't tile like one in the tutorial. Any tips for creating infinite background with tiling and tweaking offset? What am I doing wrong? |
0 | What can cause shadow slicing while moving camera? Can't explain better than with video https youtu.be 4nIMIL6w 0M The effect I'm trying to achive is a simple fog of war. See, I have a point light casting shadows on a plane. The plane has a shader which takes light attenuation and either draws a black pixel if there is no light, or discards a pixel to draw background if the light touches that pixel. After hours spent on this, I came up with a thought that I cannot do anything more. A problem as I see it Light successefully casts a shadow of shadow casters on a plane, however, with camera at a distance from the shadow, the shadow it self gets splitted and sliced, like it would've been, if some of the shadow casters' faces are suddenly removed from their meshes. What I have tried Changing Z coordinate of a light. Changing Z height of obstacles (shadow casters). Changing vertices on the obstacles so that every face would have its own vertices so no faces could share a vertex. Changing shadow quality in the settings. Changing camera rendering mode, all four of them. Changing point light to a spot light with wide cone radius. Using nice and simple standart unity's shader for a shadow receiver (a plane) Standart Diffuse. Switching between hard and soft shadow types. Changing light's shadow's resolution, shadow strength and biases Trying out the compiled EXE on another machine. Changing light's baking type, rage and intensity. You name it. None of those had any improvementes on an issue. I would like to hear authoritive replies (best option would be from the developers) as well as any information you guys think I can try out (so I can do that). |
0 | Stop Animated Tile from looping Unity2D C I am using the animated Tile script and starting the animation when I need it, by replacing a static tile with an animated one. Currently on collision with the player, however, I need the animation to run to its end and then stop when it finishes. My current code is trying to find if the current sprite on the position is the same as the last one of the animation and if that is true it should just replace it with a static tile. However, that happens instantly after the animation has been triggered. Check if the animation is finished if (playingAnimation) if (tilemap.GetSprite(lastPPosition) destructableLast.sprite) if animation ended Debug.LogWarning("Destructable Animation finished Returning to end sprite") tilemap.SetTile(lastPPosition, destructableLast) playingAnimation false Code for setting the animated tile private void AnimatedTile Destroyable(TileBase type, Collision2D collision, Vector3Int pPos) if (type destructable0) tilemap.SetTile(pPos, destructable1Animation) lastPPosition pPos playingAnimation true I did find this in the Animated Tile script public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData) tileData.transform Matrix4x4.identity tileData.color Color.white if (m AnimatedSprites ! null amp amp m AnimatedSprites.Length gt 0) tileData.sprite m AnimatedSprites m AnimatedSprites.Length 1 tileData.colliderType m TileColliderType Which confuses me, because from what I see, the sprite that is used as the animated tile sprite is the last one from the animation. Shouldn't the sprite change constantly when the animation plays, and is there a way to stop the animation once it has finished? |
0 | How should I organize 2D sprites? I'm using a Unity Tilemap in my 2D game, and I have several hundred 32x32 sprites. Most of the examples I've seen using sprites have a few consolidated sprite sheets that contain all of the game's sprites. For instance, I'd have a few 1024x1024 sprite sheets that contain all of my game's sprites. Those examples all say that the reason to do it this way is that performance is improved when sprites are packed together like that. The problem with these large consolidated sprite sheets is that it's difficult to find the sprites that I want when I'm making a tile pallet or animated scripted sprite. For example, I have two 1024x1024 sprite sheets called "House Interior 1" and "House Interior 2" that contain all my walls, floors, furniture, doors, windows, and miscellaneous interior objects. Now I want to create one Unity tile pallet that has only tiles for western style houses and one tile pallet that has only tiles for eastern style houses. Each tile pallet is going to require some, but not all, sprites from both of my sprite sheets (House Interior 1 and House Interior 2). Additionally, I want to create some animated tiles. Each animated tile will use a few sprites from somewhere in the middle of one of the large sprite sheets. My problem is that each sprite sheet image has so many child sprites that it becomes very tedious and time consuming to visually scan through each huge sprite sheet to find the tiles I want, and then drag each of them individually onto my tile pallet. Making animated tiles results in the same problem because when I assign each animation frame, I have to find the correct sprite from a huge list of sprites that are named House Interior 1, House Interior 2, House Interior 3, and so on. I'd like to have smaller sprite sheets that only contain one specific type of sprite, rather than huge sprite sheets of often unrelated sprites. For example, I'd like to have one sprite sheet that has only masonry walls, one that has only brick walls, one that has only the animation frames of a fireplace, and so on. That way it'll be easier to build up Unity tile pallets by dragging several sprite sheets into the tile pallet in the Inspector, and it'll be easier to find my animated tiles because I can easily find the sprites named Fireplace 1, Fireplace 2, and Fireplace 3. So my questions are How big of a performance hit will I experience if I don't pack my tiles together into a few big spritesheets? Is it even worth taking this into account considering modern devices are so powerful compared to what is necessary to do sprite based graphics? Is this a case of balancing the pros and cons of both methods, or is it generally strongly recommended that I large consolidated sprite sheets? |
0 | How to show NGUI menu in the upper of a Game Scene? I am new to Game Development. I made a menu with NGUI plugin. I have a background image in the behind of this menu. Now, I want to place my Game Scene in place of the background image. I have tried in several ways. But, Failed. Any suggestions will be highly appreciated. Thanks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.