_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Activate and Deactivate Collider with Click I'm having some trouble working with this, it's basically a sword that points toward your mouse position, and when you Left Click, a Trigger Collider is activated and then deactivated, but I can't get it to work. Here is my code void Attack() Activates the Sword Collider polygonCollider2D.enabled true Debug Line Debug.Log("Collider Active") StartCoroutine(Wait(0.1f)) polygonCollider2D.enabled false IEnumerator Wait(float seconds) yield return new WaitForSeconds(seconds) I did it this way hoping that the Wait method would give the game enough time to react to an active collider, and using some Debug.Log(). I know that the collider actually activates, but it does not react to other colliders. I keep wondering if this is the proper way of working with this. If it's not, do let me know.
|
0 |
How do I use Android's adaptive icons in Unity? As of API 26, Android uses something called adaptive icons. When targeting API 25 and lower, my app's icon looks fine But when targeting API 26 , it shows up in a white circle like so How can I target API 26 while utilizing Android's adaptive icons? What if I want to target API 26 , but not use Android's adaptive icons?
|
0 |
trying to get an int grid of values from unity tilemap I'm trying to get a 2 dimensional grid of values from a tilemap and found this which seems to do the trick tileMap gameObject.GetComponent lt Tilemap gt () foreach (var position in tileMap.cellBounds.allPositionsWithin) Debug.Log(gameObject.name " " position) TileBase tile tileMap.GetTile(position) if(tile.name ! null) Debug.Log(tile.name) However, something strange happens as it produces two values, when I only have one tile on the tilemap and when I uncomment my .name log above it only works for the second value and errors for the first. Any help of the best way of finding values from tilemaps would be great.
|
0 |
camera.render reads a file in the middle of a gameplay Why does camera.render read a file in the middle of a gameplay? This causes a lag in my game
|
0 |
RenderPipleinManager.DORenderLoop Internal() Taking Unusual Amount In profiler I am developing for WebGL and for optimization purposes I have converted to URP. After converting the tri count has dramatically improved but the problem is my FPS is not improving. I tried to profile and found that RenderPipleinManager.DORenderLoop Internal() is taking 13 . Is this normal? An initial search brought that it was a bug and fixed in a later unity version. But even after converting to the latest lts 2019.4.20, i am getting the same issue.
|
0 |
Using Quaternions What can I do with them? (without the maths) I am a Game Developer and did not study Mathematics. So I only want to use Quaternions as a tool. And to be able to work with 3D rotation, it's necessary to use Quaternions (Or Matrixes, but let's stay at Quaternions here in this Question). I think it's important for many developers to use them. That's why I want to share my knowledge and hopefully fill the holes I have. Now.... So as far as I understood A Quaternion can describe 2 things The current orientation of a 3d Object. The rotation transformation a Object could do. (rotationChange) You can do with a Quaternion Multiplications Quaternion endOrientation Quaternion rotationChange Quaternion currentOrientation So for example My 3D Object is turned 90 to left and my rotation I multiply is a rotation 180 to right, in the end my 3D Object 90 is turned to right. Quaternion rotationChange Quaternion endRotation Quaternion.Inverse(startRotation) With this you get a rotationChange, which can be applied to another Orientation. Vector3 endPostion Quaternion rotationChange Vector3 currentPosition So for example My 3D Object is on Position (0,0,0) and my rotation I multiply is a rotation 180 to right, my endposition is something like (0, 50,0) . Inside that Quaternion there is a Axis and a rotation around that axis. You turn your point around that axis Y Degrees. Vector3 rotatedOffsetVector Quaternion rotationChange Vector3 currentOffsetVector For example My start direction is showing UP (0,1,0), and my rotation I multiply is a rotation 180 to right, my end direction is showing down. (0, 1,0) Blending (Lerp and Slerp) Quaternion currentOrientation Quaternion.Slerp(startOrientation, endOrientation , interpolator) if the interpolator is 1 currentOrientation endOrientation if the interpolator is 0 currentOrientation startOrientation Slerp interpolates more precise, Lerp interpolates more performant. My Question(s) Is everything I explained until now correct? Is that "all" you can do with Quaternions? (obv. not) What else can you do with them? What are the Dot product and the Cross product between 2 Quaternions good for? Edit Updated Question with some answers
|
0 |
What is the easiest way to find a child? using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() int counter 0 imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) NOW INSIDE THE FOR LOOP string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName go.GetComponent lt RawImage gt ().texture thisTexture Here to assign the fileName to the go(saveSlotPrefab) Text child counter Update is called once per frame void Update() This screenshot show example of fileName content And this screenshot show the part of the file name I want to extract and assign to the text And this screenshot show how the prefab s are built the Text I want to assign to the file name part is the second child of the prefab. This prefab is the prefabs I'm Instantiating (saveSlotPrefab)
|
0 |
Questions about scaling in a 2d game in unity Okay, so I am making an android game. I want everything to scale to the size of the screen I'm using. Further, my static background needs to scale (as well as every other object), but if the aspect ratio is less than the AR of the background image I want the image to be cut off at the edges. Further, I have a game object I need to always be at the corner of the screen. I'm guessing I should use a script to determine the width of the screen and place it a few coordinates up and right of that on start? The game is only in landscape mode if that matters. How do I go about this? I previously had the background as a plane with an image on it but it didn't take up the whole screen and I think it might not be the right thing to do? Maybe use a quad? How do I test to make sure that this works? I only have my one android phone to test it on.
|
0 |
Is there a way to run Unity without rendering the scene on the monitor (headless)? I am doing some machine learning and I get my environment from Unity in the form of images but the training is taking too long and it keeps me from doing anything else on my system. Is there a way to hide the simulation rendering? Any help will be highly appreciated.
|
0 |
Unity2D Placing text HP and health bar over character sprite I've got a 2D character sprite that I will move through a game board. I want to add over it, in a corner of the sprite, a Text object with the remaining HP of that character and also a health bar. I want those elements to move with the Character. Wherever the character moves, the UI follows. I've tried adding a Text element in World Space and attaching it to the character sprite, but the Text is so huge that it's not displayed properly on top of it. I need to know how to adapt that text to the size of the sprite and how to make it follow it automatically. I guess that by setting the ch sprite as parent of the Text canvas it would work, but I don't know how to get it working. Thanks in advance
|
0 |
Strange I'm getting exception but the scripts in the exception message are not exist on my pc. What should I do? I'm using unity version 2019.2.5f1 personal I searched on my hard disks the entire pc and none of the scripts in the exception message are exist. And the exception is happens only sometimes. When I stop the game in the editor by pressing the play button the exception is show sometimes and sometimes not. I tried to close and open over agai the unity editor and the project. Still strange. MissingReferenceException The object of type 'ReflectionProbe' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEditor.ReflectionProbeEditor.OnPreSceneGUICallback (UnityEditor.SceneView sceneView) (at C buildslave unity build Editor Mono Inspector ReflectionProbeEditor.cs 651) UnityEditor.SceneView.CallOnPreSceneGUI () (at C buildslave unity build Editor Mono SceneView SceneView.cs 3359) UnityEditor.SceneView.DoOnPreSceneGUICallbacks (UnityEngine.Rect cameraRect) (at C buildslave unity build Editor Mono SceneView SceneView.cs 1935) UnityEditor.SceneView.OnGUI () (at C buildslave unity build Editor Mono SceneView SceneView.cs 2320) System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object parameters, System.Globalization.CultureInfo culture) (at lt 599589bf4ce248909b8a14cbe4a2034e 0) Rethrow as TargetInvocationException Exception has been thrown by the target of an invocation. UnityEngine.UIElements.UIR.RenderChain.Render (UnityEngine.Rect topRect, UnityEngine.Matrix4x4 projection) (at C buildslave unity build Modules UIElements Renderer UIRChainBuilder.cs 238) UnityEngine.UIElements.UIRRepaintUpdater.DrawChain (UnityEngine.Rect topRect, UnityEngine.Matrix4x4 projection) (at C buildslave unity build Modules UIElements Renderer UIRRepaintUpdater.cs 66) UnityEngine.UIElements.UIRRepaintUpdater.Update () (at C buildslave unity build Modules UIElements Renderer UIRRepaintUpdater.cs 54) UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTree () (at C buildslave unity build Modules UIElements VisualTreeUpdater.cs 72) UnityEngine.UIElements.Panel.Repaint (UnityEngine.Event e) (at C buildslave unity build Modules UIElements Panel.cs 637) UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at C buildslave unity build Modules UIElements UIElementsUtility.cs 240) UnityEngine.UIElements.UIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C buildslave unity build Modules UIElements UIElementsUtility.cs 78) UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at C buildslave unity build Modules IMGUI GUIUtility.cs 179)
|
0 |
Elegantly exposing properties in Unity inspector There are various game objects in my scene that share some common characteristics, so I created an interface, like so public interface IHasLimitedRangeOfMotionAlongZAxis float MinimumZ get float MaximumZ get For certain types that implement this interface, I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector. Therefore, I would like to be able to expose these properties in Unity. I am aware that one approach is to write C scripts in the Editor folder to implement an ExposePropertyAttribute (see here). However, this approach is unsatisfactory for two reasons My solution is not co located with my Assets folder. I write my code in a separate solution, and then use pdb2mdb.exe to import my scripts into my Unity scenes. (The reason for doing this is to avail myself of C language features introduced beyond C 4.0, which nonetheless target .NET Framework 3.5.) I shall have to create a custom editor for every single type that implements the interface with publicly assignable properties. This leads to a lot of boilerplate code. Is there a more elegant approach than adding private backing fields with the SerializeField attribute for all of my public properties?
|
0 |
UV Tiling Offset input values from World Position incorrect behavior? I'm using ShaderGraph in 2020.1.0f1. I have some shader experience, but it's all been handwriting shaders. I have experience with node based things of this nature by way of Substance Designer. I'm working on a shader that should allow for seamless visibility between quads by changing the UV offset of a noise pattern based on the world position of the quad. That said, I'm running into two things. This short (0 05) video shows how I'm expecting this to work as the X Y values of the UV Offset are changed, the continuous flow of the noise is smooth. https youtu.be YAd9BtAWVRM So, I add a position node and a split node, feed the world position into the split, and feed R G from the split to X Y of the Vector2 node. That does two things it makes the preview boxes 3D (becomes a sphere instead of a quad), and quot expands quot the apparent tiling I'm guessing this is because the value from the split is a Vector1 rather than a float, though it seems odd that there's no implicit conversion, or that Vector1 values applied to UV Offset would change the actual appearance. So, is this due to it being a Vector1 rather than a float? If so, is there a node that can convert from Vector1 to float? Am I going about this the wrong way entirely?
|
0 |
How to write properly shader with gradient based on vertex color? I took 4 squares with the outer corners painted in black, and the other ones in white. For some reason, they have a different gradient. fixed4 frag (v2f i) SV Target fixed4 mainTex tex2D( MainTex, i.uv) fixed4 overTex tex2D( OverTex, i.uv3) fixed4 final fixed4(lerp(mainTex.rgb, overTex.rgb, overTex.a) i.color, 1.0) final lerp(float4(0, 0, 0, 1.0), final, i.color.a) shadows return final How can i make the same gradients as bottom left and top right? In game this is faces of blocks (like minecraft) and gradients is smooth shadow light. So I cannot change tris
|
0 |
Unturned weapon modification not spawning in singleplayer I've been working on my first modification for Unturned and I'm having some serious trouble doing the process due to the lack of up to date tutorials on modding weapons. I've done everything I can to make it, and I was finally able to create a bundle and export the .unity3d file into the copied folder for my modded gun. However, when I go into Unturned and actually attempt to spawn it, nothing works. I'm assuming it's the version of Unity that I'm using (Unity 5 2.4), even though I followed the instructions correctly while in the editor. Please help, I really need a solution, because I've been at it for weeks now and no one has been able to provide any solution.
|
0 |
Dynamically applied texture to GameObject using GUI button In a scene I have multiple different GameObjects (almost 30 kinds) with parent child relationships. At run time (by using a GUI button) I want to change the texture of each clicked GameObject. As the user clicks specific GameObjects, a GUI with a multiple texture button will appear. By clicking on the button, that specific texture will be applied. Is there a smarter way to do this? Do I need to apply a script to every object? I have tried to apply a script with some specific code it's working but not regularly and correctly. Additionally, I want different texture options for each kind of GameObject.
|
0 |
Selling merchandise inside game? I am developing my first iOS game on Unity. I spent a lot of time creating beautiful artwork for the game (characters and scenery). I gave testflight access to my friends and advisors, and they loved the game art, and asked me if I have ever thought about selling t shirts or something. I did some research, and found three services offering a SDK or plugin that lets me sell merchandise inside the game themonetizr.com merch.amazon.com First I thought about using Amazon, but then I saw that the monetizer actually lets players buy right inside the game (which is nice, as I would hate users to be directed to their browser) and they a lot more products, like phone cases. Have you guys used any of these services before? How hard are they to integrate? Thanks!
|
0 |
Unity How to Hide "Editor Script" in the Inspector? I want to hide the "editor Script" in the Unity Inspector, so it doesnt show up with all the other components (transform other scripts etc.) It works with every other "normal" component like this component.hideFlags HideFlags.HideInInspector but when it comes to the Editor Script it just doesnt hide. EDIT My Custom Editor Script using UnityEngine using System.Collections using UnityEditor ExecuteInEditMode CustomEditor(typeof(DetailCamContScript)) public class CamEditor Editor public override void OnInspectorGUI() DrawDefaultInspector() DetailCamContScript myScript (DetailCamContScript)target if (GUILayout.Button("Set Camera Active")) myScript.setCamActive() EDIT Problem solved. the problem was The editor script was attached to a Gameobject. It doesnt needs to be attached.
|
0 |
In Unity, how do I make a 3D flight arc preview? I'm stuck on how to make a preview trajectory for a projectile appear when holding a button. The trajectory should start at a certain position on the scene and end wherever the player points their mouse. On mouse click, a projectile should be launched along that trajectory with the clicked position as its target. How can I do this?
|
0 |
Issues with importing bezier curve animation (curve does not distort?) Hi guys i'm pretty new to unity and having a frustrating issue I've created a spear gun with an animation using a bezier curve grouped to the main gun shaft and distorted using a bone (bone relative) in blender. It works fine in blender, however when I export it into unity 5, the bezier curve does not distort and simple moves forward and back. I imported the blender model as a blender file. I have tried pairing the model components in all the ways i can think of to see if that was the problem? I have attached the blender views and animations and what it looks like in Unity. Is it an issue with unity being unable to animate bezier curve animations or the type of bone pairing i used?? unity animation, see the besiel curve simple moves forward and back instead of bending distorting to look like a rubber fitted on a real gun!
|
0 |
Unity crossplatform native plugins I need to create a c native plugin for my game. If I want to support macOS and Windows, do I need to write my plugin twice one in XCode with a bundle project and another in VS for windows or is there a way to support both with one codebase?
|
0 |
Removing FMOD from a Unity WebGL project causes an error about not being able to copy fmod register static plugins.cpp When I imported the FMOD plugin into a Unity WebGL project, then removed it afterwards, I wasn't able to build it due to errors about trying to copy an FMOD file fmod register static plugins.cpp Restarting the editor, reimporting everything, deleting Library Temp folders did not help. Neither did deleting the FMod folder.
|
0 |
Rendering hundreds of animated characters in Unity3D I am currently doing some research in anticipation to the development of a game where there is going to be hundreds of secondary entities which will interact with the player and among themselves (little soldiers with a very simple AI and not too many faces). What I've found so far is that there is a way of avoiding the GameObject overhead, at least for the rendering bit of things, by using the Graphics class, with the Drawmesh method more specifically. I've tested it and it's not too complicated. I could render any of my models using it and then make them move by rendering the graphics around coordinates in some non unity "Character" object. The fact that the drawmesh call has to be every frame is actually quite convenient in this case ! However, I've ran into a problem how do I deal with animated objects ? Now, I've also done some research on that, and what I've found is that you can "Bake" the skinned mesh into a mesh usable with Graphics.Drawmesh. Then I thought about rendering animated far away characters by updating their mesh with their current animation at a certain interval. This would make the character look wierd but at long distances and among many others it should render quite well. But the thing is, since I don't want to create a GameObject for each entity, or more precisely only for the ones up close that need a collider and everything so the players can target them with a raycast. And I sure as hell don't want to create a skinned mesh renderer for each far away character, as it would defeat the point of using Graphics.Drawmesh. I've thought about one solution to this problem I could have one "hidden" GameObject with the proper models and animations get requests from "Optimized", meaning far away character to set himself to a certain frame of a certain animation, bake his mesh and send it back to whoever requested it. I did not run any tests with that solution (I came up with it while writing this) but I'm kinda afraid that updating the mesh of a single entity potentially hundreds of times per frame might lead to wierd behaviors. Besides, I'd have to put it far away so that it doesn't get found by the players. So, my exact question is Do you have any better idea as to how I could optimize rendering all those characters some other way, and if not, is there a way to ask Unity "what would this mesh look like on this frame of this animation", thus allowing me to avoid creating a Gameobject just for that. Thanks a lot in advance ! Cheers !
|
0 |
Any problems with flipping a sprite by scale? (2d Platformer) I am wondering if there are any problems with flipping a sprite on the x axis using vector2 to tell which direction it is facing flip. Though doing this helps me write less code for Ray cast direction and creating single states with a single animation (using 1 animation player facing right than using 2 animation facing left and right). If there is a better solution please tell me and thanks. Btw I am still pretty new and learning.
|
0 |
Lights not displayed on Sprite I have a scene that contains 3 elements Main Camera A 2D Sprite that renders a single white pixel image, scaled to 2000 x 1000 A point light with a yellow color What should be done so that the light is actually rendered on the sprite? I have recorded a short video showcasing the issue https www.youtube.com watch?v g2iZB6BXhPs
|
0 |
Trivial and efficient sprite animation in Unity I'm looking for an efficient way to create and use simple sprite animations in Unity. My situation is the following I have lots of entities (thousands) which need to be animated. These entities have the same (identical) animation running, which involves just sprite swapping. The animation loops endlessly. The following gif represents an example of what I need. In this example, a single animated object is placed on each tile. Because of the number of objects, I would prefer to not have an animator animation combo on each, and I would prefer not to have a MonoBehaviour on each. The overhead from both of these solutions will be way more than the game could handle. The required effect requires just a looping sprite swapping animation, which can simultaneously run on thousands of objects. The gif above was made with animator animation combos on each object. The features offered by Unity's Animator component are great, however way beyond what I need here and thus the overhead is not worth it. Optimisations I am aware of Disabling animators when zoomed out. Disabling animators on objects which are out of view. Merging multiple objects into a single one which spans multiple tiles (does not apply due to nature of game) Writing my own sprite swapping animation component (not inherited from MonoBehaviour, similar in idea to this code), placing it on each item. Then creating an AnimationController object (inherited from MonoBehaviour), which updates all instances of my sprite swapping component at regular intervals. This is the solution I will likely go for if nothing else comes up, however involves hand crafting animations, delays between sprites and such, which will be time consuming. I feel as though others have surely come across this problem before, so I'm wondering how you solved it. Please also let me know if using Unity's built in animator animation system is in fact less resource intensive in this situation than I think. Thank you!
|
0 |
Changing text through a cursor hover trigger In my game I have several house groups (see image below), I want to show a specific message when the mouse hovers a specific house group. For some reason, this only works on the first switch case (house) but fails on the second switch (house2). The default case doesn't work either. I verified that the case house2 is found by the engine. By not working I mean the text does not appear. Do you have any idea about the problem? Code public class MouseIsOver MonoBehaviour private Image TipImage private Text textObject public string text private bool displayInfo void Start () TipImage GameObject.Find("realtyInformation").GetComponent lt Image gt () textObject GameObject.Find("realtyInformationText").GetComponent lt Text gt () TipImage.enabled false void Update() Display() void Display () if (displayInfo) switch (text.ToLower()) case "house" textObject.text "house text1" break case "house2" textObject.text "house text2" break default textObject.text "Click on the building" break else TipImage.enabled false textObject.text "" TipImage.enabled true private void OnMouseOver() displayInfo true private void OnMouseExit() displayInfo false
|
0 |
Unity Sprite stretch issue I have a simple png square 8px x 8px. In Unity I've left the pixels per unit at 100 and added the image to the scene to create a prefab of the item. I then add four items to the screen like so var block Resources.Load( quot Prefabs Block quot , typeof(GameObject)) Instantiate(block, new Vector3(1f, 0f), Quaternion.identity) Instantiate(block, new Vector3(0f, 1f), Quaternion.identity) Instantiate(block, new Vector3(2f, 0f), Quaternion.identity) Instantiate(block, new Vector3(0f, 2f), Quaternion.identity) The results (as shown in the image below) seem to stretch the image dependant on where the prefab is placed. Is this normal behaviour? Is there a way round this or something I'm missing?
|
0 |
Is an iOS development license with Unity free? I'm coding in Unity Personal and I'm going to try to put my game onto the App Store (through the Unity XCode App Store process). In the past, Unity has charged money to get a iOS license for this. The price was 400 I believe. I've certain articles that say that it has changed, and some that say it still costs money. So, I'm not sure which one is true. Is creating and publishing a commercial game with Unity Personal now free? (meaning that there is no license required). If there is a price, how much is it, and is it a one time fee or per month year game published etc. Thanks! Also, can I legally make money with this game using the Unity Personal?
|
0 |
Unity .3ds file is purple I imported a .3ds file from skethup and in the preview it shows it with the texture, but when I put it in the scene it shows it without the texture. http puu.sh gyYSU a09541420c.png
|
0 |
Why the renderers Renderer array are all null? using System using System.Collections using System.Collections.Generic using UnityEngine public class LightsEffect MonoBehaviour public List lt UnityEngine.GameObject gt waypoints public int howmanylight 5 public Generatenumbers gn public bool changeLightsDirection false public float delay 0.1f private List lt UnityEngine.GameObject gt objects private Renderer renderers private int greenIndex 0 private float lastChangeTime private void Start() waypoints new List lt UnityEngine.GameObject gt () objects new List lt UnityEngine.GameObject gt () if (howmanylight gt 0) UnityEngine.GameObject go1 UnityEngine.GameObject.CreatePrimitive(PrimitiveType.Sphere) duplicateObject(go1, howmanylight) LightsEffects() private void Update() LightsEffectCore() public void duplicateObject(UnityEngine.GameObject original, int howmany) howmany for (int i 0 i lt waypoints.Count 1 i ) for (int j 1 j lt howmany j ) Vector3 position waypoints i .transform.position j (waypoints i 1 .transform.position waypoints i .transform.position) howmany UnityEngine.GameObject go Instantiate(original, new Vector3(position.x, 0, position.z), Quaternion.identity) go.transform.localScale new Vector3(0.3f, 0.1f, 0.3f) objects.Add(go) private void LightsEffects() renderers new Renderer objects.Count for (int i 0 i lt renderers.Length i ) renderers i objects i .GetComponent lt Renderer gt () renderers i .material.color Color.red Set green color to the first one greenIndex 0 renderers greenIndex .material.color Color.green private void LightsEffectCore() Change color each delay seconds if (Time.time gt lastChangeTime delay) lastChangeTime Time.time Set color of the last renderer to red and the color of the current one to green renderers greenIndex .material.color Color.red if (changeLightsDirection true) Array.Reverse(renderers) changeLightsDirection false greenIndex (greenIndex 1) renderers.Length renderers greenIndex .material.color Color.green In this line if for example objects count is 5 then there will be 5 renderers but they will be all null. renderers new Renderer objects.Count
|
0 |
Convert Minimap render texture to 3d space position I am using Render Texture to make a Mini Map it is working fine. Now I want world space position from render texture click point. Is there any way available that I get the world space position from the render texture's specific click point? If I click somewhere in render texture then, how can I get that point in 3D world space? For example, I click a car object on render texture How can I highlight or get it in 3D world space.? Update Actual Scenario is One Main Camera Rendering the Scene. NGUI Camera Rendering the GUI. That GUI contains the Render Texture(minimap) which rendering the scene on texture using GUI Camera. Now how can I get 3D position from 2D render texture!
|
0 |
How to create temp folder to store a file from external directory and use it in a game I would like to copy a 3D model from external library and save it in temp Resources StreamingAssets folder to instantiate an object in unity scene. public class FBXOBJLoader MonoBehaviour string src Use this for initialization void Start () src EditorUtility.OpenFilePanel("Select Model", "", "fbx") Output the Game data path to the console Debug.Log("Path " src) StartCoroutine("CopySomething") IEnumerator CopySomething() print("Start") string path path Application.temporaryCachePath FileUtil.CopyFileOrDirectory(src,path) yield return null It's creating some unknown file format in the asset folder. can anybody please help me to complete this task. Thanks in advance
|
0 |
Player with navmeshagent keeps moving back to the last mouse position clicked On my FPSController I have two scripts, Player Controller and Agent Controller. Player Controller is for using the keys WSAD for moving the player around. Agent Controller uses a NavMeshAgent to move the player to a position clicked with the mouse (like point and click ). Everything is working fine, or was working fine until I tried to move the player around using the keys WSAD after clicking the mouse. I clicked the mouse on the ground (terrain) or on a cube no matter what I clicked on and the player is moving to this position. Now at that position the player stops. Now I'm trying to move the player with the keys WSAD, but even if I click on S for example long time the and player is far away from the last mouse clicked position when I leave the S key the player automatically moves back to the mouse clicked position. The player should stay at where I move him with the keys WSAD but he keeps moving back to the last clicked mouse position. On the FPSController I have a Rigidbody and NavMeshAgent and the two scripts Player Controller and Agent Controller. The original Agent Controller script was using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.AI public class AgentController MonoBehaviour public Camera camera public NavMeshAgent agent public bool agentControl false Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetMouseButtonDown(0) amp amp agentControl true) Ray ray camera.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) agent.SetDestination(hit.point) And the Player Controller script using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour public float speed 10.0f Use this for initialization void Start() Update is called once per frame void Update() float translatioin Input.GetAxis("Vertical") speed float straffe Input.GetAxis("Horizontal") speed translatioin Time.deltaTime straffe Time.deltaTime transform.Translate(straffe, 0, translatioin) if (Input.GetKeyDown("escape")) Cursor.lockState CursorLockMode.None The main goal is to use either the Agent Controller for point and click with the navmeshagent or using the keys WSAD to move around.
|
0 |
Adding Animation to Object Unexpected Behavior I've been following the Unity 2D roguelike tutorial and I'm a bit confused about something. When he drags a series of sprites to his player object, a dialog box appears that prompts him to name and choose a location for his animation. I have seen this behavior in a couple video tutorials now. When I do this, it simply creates the animation and animation controller in the sprite folder and nothing more. This becomes a bit tedious after a while and I'm not sure these animations are being associated with the object correctly. What am I doing wrong?
|
0 |
How could I format my C code using Checkstyle? Is there any possible way to check my C code with Checkstyle in the context of Unity?
|
0 |
Teleport Not Working in Unity 2D So I'm basically trying to get my character to "use" a set of stairs by teleporting from one stairway door to another. Each stairway door will be paired with one other stairway door. Here's the code, I feel like it should be working...my Debug.Logs are even outputting the correct information. Also FYI, I have the Transform doorPairedWith as public so that I can just drag and drop the stairway door that each one is supposed to be paired with. using UnityEngine public class Stairs MonoBehaviour Player player public Transform doorPairedWith Vector3 doorPairedWithPosition Vector3 playerPosition BoxCollider2D playerCollider BoxCollider2D stairsTriggerCollider bool playerIsNearStairs false void Start() player Player.instance playerPosition player.transform.position doorPairedWithPosition doorPairedWith.position playerCollider player.GetComponent lt BoxCollider2D gt () stairsTriggerCollider GetComponent lt BoxCollider2D gt () void Update() UseStairs() void UseStairs() if (playerIsNearStairs true) if (Input.GetKeyDown(KeyCode.E)) Debug.Log("Attempting to use stairway door named " doorPairedWith) playerPosition doorPairedWithPosition void OnTriggerEnter2D(Collider2D collision) if (collision.gameObject.tag "Player") playerIsNearStairs true Debug.Log("Player is near stairs " playerIsNearStairs) void OnTriggerExit2D(Collider2D collision) if (collision.gameObject.tag "Player") playerIsNearStairs false Debug.Log("Player is near stairs " playerIsNearStairs)
|
0 |
SpriteRenderer not Rendering Sprite Edit I've slightly edited this question because I've found the symptom for my problem, but not why the actions I've noticed cause the issue. I have what appears (via the inspector) to be two identical 2D objects containing only a transform and a Sprite Renderer. One was created by dragging a png from a folder onto the screen, and it displays normally. The other was created by going to the hierarchy and right click 2D Object Sprite, and dragging the desired picture into the object's 'Sprite' Field. Both objects appear in the development view, but only the first one appears in the game view. Why does the second object not appear? All other settings for Unity (environment, camera, etc) are the default for a 2D project. Here are the inspectors for... The sprite that is displaying The sprite that is not displaying And my Camera
|
0 |
Prefabs moved to before position when zooming scene I have build some pipes for waterline drawing, like following screencast https youtu.be WnJb1JwOW78 As you can see, when I zoom in the scene, Pipes moved to lower position. When i zoom out, Pipes moved to higher position. Actually I have changed the position and moved down the pipe position before, the unexpected higher position was the pipe before position. So i guessing this problem might about cache clean. So I I try to clear the GI cache, but the problem still exist. And then I try to build a windows executable file and run game again, problem still. How to fix it? I am using Unity 2018.4
|
0 |
How do I get objects using layer name? I am creating an FPS game in local multiplayer. One player creates the hot spot game, and the other one connects through WiFi network and plays the game. I want to find all of the player objects on the network that have a specific layer name, and store them into an array when the player spawns on the network. I've been able to add the object to the array, but I can't find the layer's objects with what I found with Google searches. LayerMask.NameToLayer("LayerName") LayerMask.LayerToName(8) This returns the name of layer and layer index. How can I get the objects using a specific layer name, and also store it in to an array?
|
0 |
Components accessing Game state and other global data I have the following example component public class DoStuff MonoBehaviour public GameManager Data data to be shared among components and scenes, public bool Predicate() return Data.State Idle public void Execute() if (!Predicate()) return Do stuff It needs to access data that I have in a data class (not a component) called GameInfo, which the GameManager creates on start. What is the 'best practice' for accessing data like that in a unity component. Make GameInfo static (or Unity equivalent) Drag the GameManager GameObject from my Scene on this component from the Editor Use FindObjectOfType(typeof(GameManager)) to find the data on Awake Start Turn GameInfo into a component and attach to empty GameObject in my scene, then follow 2. Some other method? Thoughts Having come from working on Internal tools and webservices, making things Static is rarely a good idea, but maybe for Game development making my global game state data static is the exact thing to do. I don't have any problems with this other than it just feels strange, but that's probably just due to being new to this mindset. I believe this uses reflection to search, which if only done once at start would be no big deal, but I feel this option is less nice than 2.
|
0 |
How To Architect My Game To Keep the Same Scene Loaded My Unity game has a large planet GameObject that serves as the map. I want to keep this planet loaded, but still create different levels where enemies and the player are spawned at different locations on the planet, depending on the level. Therefore, the objectives, targets, and vehicle the player must use and accomplish are different at each level, but the map itself is not. I have had a couple of thoughts. My first idea is to use transforms as locations for where vehicles spawn, and assign a vehicle to each location. Perhaps then each set of locations can be saved as a prefab that represents a level. One possible solution is to use different scenes for every level, with the main scene containing the planet being kept throughout. I am not sure how the different components can communicate with each other, however. My difficulty with all this is how to conceptualize how all the elements will work together. Say I make a class called Level, which includes the Objective that must be accomplished to win, the Vehicle the player will use, and the Locations where objects are to spawn, etc. Then I create scripts called Level1, Level2, etc. that inherit from Level and allow custom scripting for each level. However, there is also a state where the menu shows the scene, but no objective is being accomplished. Is that a viable solution? Is there a better solution from experience?
|
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 |
What is the difference between Serializable, and System.Serializable? What is the difference between Serializable, and System.Serializable? I'm guessing SerializeField is only for attributes of a class. What is the difference between the above two, then?
|
0 |
A pathfinding for dynamic obstacles and player made blockages? Hi I'm creating a TD in Unity 5 and need some help with my Pathfinding. I'm going to use Arons A pathfinding for my AI which enables me to use dynamic objects and update the path during run time. However in my game I want the player to be able to block the minions with special turrets which will force the minions to attack the "block tower" instead to get past to their destination. How could I accomplish something like this? Image for more clarity
|
0 |
Low fps on Arm Mali GPU I was trying to google and understand my problem in two weeks but i am defeated, so i am asking for help. The main problem is that my custom unlit frag shader after certain amount of time on devices with mali gpu starts to drop fps i see it via fps counter in the cpu section. I dont know why in that section and not in render section, but with out this fps counter i can still feel the drop of fps. So on Samsung S4, Samsung sm t 380, xiaomi redmi note 5, samsung tab s2 is all ok, the drop was only on samsung s6 to solve the problem i just half the resolution by Screen.SetResolution function. I was thinking that drawing the full screen sprite on such a high res device is the point. Then i can test app on samsung sm t580 and the drop was there this device has low resolution than S6. I assume that the problem in arm mali gpu or i am sure in my hands. So again, i am rendering full screen with draw mode tile(countinuous) sprite with 3 textures, just changing theirs uvs in vert func and apply in fragment. This makes distorting effect. The shader show that i have 10 maths and 4 textures, yes 3 textures but i am making 4 sampling. The textures are 256x256 with repeat mode. I was trying diferrent textures compressions, dxt5, etc1 2, alpha8, R5 no effect. I was trying to different precisions half and float in different parts in shader no effect. I was thinking in alpha, so i took textures without alpha and not getting it from tex2D. Even the size of textures is doesnt matter, even if they 64x64. The dance with ZTest, ZWrite, Blend, Queue RenderType, other params no effect. My guess was that maybe on mali uv TEXCOORD0 must be only float2, not float3 or float4 no effect. I am applying Time.y and replace it with float from script no effect. Only reducing amount of tex2d in shader is working. Why? What i m doing wrong?
|
0 |
How How can I make a simple combo combat system in Unity I'v been trying to make a melee combo combat system in the Unity Animator, but I can't seem to get it right. I'm trying to go for a combo system that flows from Hit 1 to Hit 2 to Hit 3, ect, with clicks from my mouse, and if I don't click again it will go back to Idle. How would I go about making this combo attack system in the Animator with Unity and C .
|
0 |
Player jitters when Jumping at object edges So I have a bit of an issue with my Player controller script. Everything works fine except with very specific jump cases. If I jump at an object and I don't reach the top edge I will just fall normally with no issue. However, when the object is short enough for me to possible jump on top of it, if I collide with its side when jumping my player will halt in that spot, jitter for a second and then fall normally. Here is my code using System using System.Collections using System.Collections.Generic using UnityEngine public class ThirdPersonPlayerController MonoBehaviour public CharacterController controller public Transform camera public Transform groundCheck Vector3 direction Vector3 velocity public float moveSpeed 10f public float turnSmoothTime 0.1f private float turnSmoothVelocity public float gravity 39.24f public float groundDistance 0.4f public float jumpHeight 3f public LayerMask groundMask private bool isGrounded Update is called once per frame Unity is currently working on a new input system private void Update() IsPlayerGrounded() float horizontal Input.GetAxisRaw( quot Horizontal quot ) float vertical Input.GetAxisRaw( quot Vertical quot ) direction new Vector3(horizontal, 0f, vertical).normalized direction player is moving if (Input.GetButtonDown( quot Jump quot ) amp amp isGrounded) Jump() MoveAndRotate() Gravity() private void MoveAndRotate() if (direction.magnitude gt 0.1f) float targetAngle Mathf.Atan2(direction.x, direction.z) Mathf.Rad2Deg camera.eulerAngles.y float angle Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime) transform.rotation Quaternion.Euler(0f, angle, 0f) Vector3 moveDirection Quaternion.Euler(0f, targetAngle, 0f) Vector3.forward controller.Move(moveDirection.normalized moveSpeed Time.deltaTime) Implemented proper gravity from y 1 2g t 2 private void Gravity() velocity.y gravity Time.deltaTime controller.Move(velocity Time.deltaTime) Check if player is grounded and reset velocity private void IsPlayerGrounded() isGrounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if (isGrounded amp amp velocity.y lt 0) velocity.y 2f private void Jump() velocity.y Mathf.Sqrt(jumpHeight 2 gravity) Current issue (Not yet fixed) When jumping against a wall the player will stick jitter (starts to jitter at the top edge). Here is a visual representation of what I mean by colliding near its top edge Any help at all is greatly appreciated. Note I thought it had something to do with objects having the Ground layer attached to them, but the bug is still present if they don't have a layer.
|
0 |
Photon2 billboards take a long time to face the camera I'm using PUN2 and trying to use nametag billboards for my players, but they are not facing forward correctly and I have to wait more than 20 seconds to make the name tag of player return to facing forward. here's my code for my BillBoard Script public class BillBoard MonoBehaviour protected Transform ThisCameraPlayerBillBoard private void Start() ThisCameraPlayerBillBoard GameSetup.GS.ThisCameraToBillBoard.GetComponent lt Camera gt ().transform private void FixedUpdate() transform.LookAt(transform.position ThisCameraPlayerBillBoard .rotation Vector3.forward, ThisCameraPlayerBillBoard .rotation Vector3.up)
|
0 |
Image target display in unity Vuforia I am using unity 4.5.1f3 and using the Vuforia sdk 5.0.5.I have downloaded the sample project from the Vuforia site.When I tried to run the sample of Imagetarget project,it asked to add license key.Then I added licensed key to the app.Then when I runned the project again its showing me and error MissingMethodException Method not found 'UnityEngine.Behaviour.get isActiveAndEnabled'. Vuforia.VuforiaAbstractBehaviour.UpdateStatePrivate (Boolean forceUpdate, Boolean reapplyOldState) Vuforia.VuforiaAbstractBehaviour.Update () The Image marker detection can run but the camera video doesn't show in the background. can anybody help me solving the issue?
|
0 |
How can I add a batch of sprites to a list in Unity's inspector? I have a C script with a public property List lt Sprite gt someSprites I would like to add 20 sprites to it, from the inspector window. However, it seems like the only way to do so is to drag one by one. Is there a simpler way to batch fill lists in Unity?
|
0 |
Character blocking when walking on cube edges I have my character walking on a ground made of cube. (scale 1,1,1). There is no space between them. Also, I have a RigidBody with 15 drag and I'm moving with AddForce. When I walk, my character sometimes block when trying to pass over the place where the 2 box meet. Like if my player collider was hitting the collider under him. Any fix for that?
|
0 |
Unity Mirror can't reflect another mirror across from it I created a mirror in Unity using the FX MirrorReflection and the script that comes with it. http wiki.unity3d.com index.php MirrorReflection4 One mirror at a time works perfectly fine, but as soon as I add another mirror in front of the other mirror it starts bugging out. See image below for the result I'm getting. Does anyone know how to fix this so that both mirrors can reflect off each other?
|
0 |
Raycast does not detect child layer if parent layer is set to ignore I have a LineRenderer that ignores certain Layers based on a Raycast using LayerMask. I have a cube with a collider on a Layer which is ignored because of the LayerMask. I have a smaller object inside the cube that is a child object of the cube and is on a layer that is not set to be ignored. I need the Raycast to hit the smaller object. When this smaller object is un parented from the larger cube, the LineRenderer behaves like I want it to the hit data informs me it is being hit by the Raycast, but this does not hold true if the smaller object is a child of the cube. Is there a way of having this behaviour without having to un parent the smaller object? It's like the smaller object is inheriting the parent's Layer, despite being on it's own Layer does this sound like what is happening?
|
0 |
How to prevent object from moving when it's mesh collider is being updated? So I a made a script that lets the player grab a vertex, move it, and then update the mesh. To help prevent the player from trying to clip it through other objects I made it so the mesh collider is constantly being updated. It works however there is an issue where it keeps falling into itself. So I tried updating the constraints to prevent this but it doesn't seem to help anything. Visualization... With the mesh being updated after the LMB is released http gifyu.com images withnocollisionprevetnion.gif (SE doesn't like non imgur links apparently and they are too big for imgur). With the mesh being updated in real time http gifyu.com images withcollisionprevetnion.gif Also here is a gif showing how constraints on the RB don't solve the problem (I've tried freezing on different axes but those still cause issues too) http gifyu.com images constprob.gif So basically what can I do to prevent the object from moving when it's mesh collider is being updated?
|
0 |
RawImage texture change event? I have a RawImage and an AspectRatioFitter attached to it so I want to change the aspect ratio to fit the image in the texture field of the raw image. But I need to avoid checking for it in the update as much as possible. Is there an event for when the texture of a RawImage element has changed? Something like OnTextureChanged().
|
0 |
Unity3d Find a point on the line which has shortest distance from the third point So, initially, I had points A and C. To get point B, I had to shoot a raycast down from point A and get the hit.point, which is point B now. Point D is somewhere between the raycast I shot from A and perpendicular to C. How do I find the point D.
|
0 |
How to sync new object (weapons bullet) in a multiplayer photon game ? I'm using Photon to develop a multiplayer game. I would like to know the best way to synchronize "weapons" bullets object between network players. Thanks
|
0 |
Spot Light color fade in Unity 3d I have a scene where many spot lights are focused on the screen. All have red color and same intensity. What I want is that the red Color(0,0,0,1) value should increase and decrease in a fading effect over a period of time. I thought of using Color.Lerp() but can not achieve it. What currently I am doing is attaching this script to all the instances of the SpotLight. void Update() if(Time.time() 120 0) transform.light.color new Color(Random.Range(0,255),0,0,1) I know I am missing something big here. Help is appreciated. Thanks in advance.
|
0 |
Reset Polygon Collider Runtime (Unity) I've created an animation by using different frames. Then applied polygon collider on that object. Problem is that when frame changes in animation, it does not reset collider. I've searched for resetting polygon collider as sprite gets change. One solution I've found is like following Destroying existing collider amp Adding new collider to the object. http answers.unity3d.com answers 723811 view.html I've applied this on the object. But it hangs the game. Is there any another way to reset polygon collider from c .
|
0 |
Change center point and size with the help of the Matrix in Unity Let us suppose I have an array of Vector3, it contains vertices. Now I want to scale the vertices and or change the center point of the texture (move texture relatively). I have a Vector3 which is a new center point and I have a Vector3 which is vector for scaling along x, y and z. How can I construct a needed matrix in Unity? I am very new to all this, so, please, in case of any misunderstanding ask me about it. Here is what I was able to find on my own. The problem with it, though, is that I can not infer what I need from it. I need a little bit more peculiar thing.
|
0 |
GameObject scope over RPC call Debugging my code I faced some unexpected behavior. I called an RPC using uLink.NetworkView on the server passing some parameter including a GameObject tagged as Player. Inside that RPC I make a call to GameObject.FindObjectsWithTag("Player") What I refer to by saying "unexpected" is that that function returns all the gameobjects in hierarchy INCLUDING the gameobject passed as parameter to the RPC call. I noticed that inside the editor it appears in hierarchy the gameobject passed to the RPC but without all the components BUT the transform. My question is to know exactly how the scope is working, I seem to understand that the scope of the FindObjectsWithTags seems to include RPC parameters but without the most informations. Any clue about this?
|
0 |
How to get the tangent and normal of a collision? In my game, one of my objects casts a ray into a 2d space. If that ray were to hit another object, I'd like to draw a line that is perpendicular to the tangent of the ray's hit point. So when the ray hits the other object, a tangent is formed at the point of contact, and then I'd like to use the linerenderer component to draw a line that is perpendicular to that tangent. I already know how to use the linerenderer to draw lines, but I don't know how to get the tangent and normal from a collision. if (Input.GetMouseButton(0)) Vector2 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) var direction (mousePos (Vector2)cueBall.position).normalized var hit Physics2D.Raycast(cueBall.position, direction, Mathf.Infinity, 1 lt lt LayerMask.NameToLayer("Ball")) if (hit) line1.SetPositions(cueBall.position, hit.point) This is the line from the cueball to the red ball. line2.SetPositions(hit.point, hit.normal) This is supposed to be the predicted trajectory of the red ball.
|
0 |
How to add caves to a terrain mesh generated with 2D noise Am I getting it right, that when I'll make a single mesh that represents terrain using unity's built in 2D Perlin noise function, then I'll be able to somehow add caves using whatever (Perlin worms for example)? Or do I need to find solution with 3d noise?
|
0 |
How do I write to z buffer in a transparent Unity 5 shader without a shadow caster? I've seen plenty of examples of "priming the depth" buffer with this pass Pass Tags "LightMode" "Always" ColorMask 0 But it does nothing in Unity 5. How do I write to the depth buffer ( CameraDepthTexture) in Unity 5 without using a shadowcasting pass?
|
0 |
Does transparency work with SSS in Unity's HDRP Lit shader? I am using Unity's HDRP Lit shader in Shader Graph (all are version 4.8.0 preview) on Unity 2018.3.0b12. I am trying to use both transparency and subsurface scattering on the material. However, it appears that the visual appearance loses SSS when transparency is introduced. Example The cube on the left has transparency enabled, and has no visible SSS. The cube on the right has the same SSS settings as the left cube, however the right cube has no transparency enabled. I need transparency to fade in the cube depending on its position, like this And here is my master node If anyone has an alternative solution that sidesteps this potential limitation, I am all ears. Cheers!
|
0 |
Why don't Sin and Cos give expected results when rotating off axis around a non uniform shape? When I rotate a rectangle and draw straight lines along it's edge using Sin and Cos the lines don't follow the edge as the angle approaches 45 degrees, why? The exact same code works just fine when I use it on a square. See Gif Left object has the same width and height, No distortion of angles. Right side has larger X axis and lots of distortion. Why does this happen and how do I prevent it? Unity code RequireComponent(typeof(Image)) class rotation MonoBehaviour SerializeField private float left 180f, up 90f private void OnDrawGizmosSelected() RectTransform rect GetComponent lt RectTransform gt () Vector3 corners new Vector3 4 rect.GetWorldCorners(corners) float rot transform.eulerAngles.z Gizmos.color Color.red Gizmos.DrawLine(corners 3 , corners 3 new Vector3( Mathf.Cos((left rot) Mathf.Deg2Rad) rect.rect.width, Mathf.Sin((left rot) Mathf.Deg2Rad) rect.rect.height)) Gizmos.color Color.blue Gizmos.DrawLine(corners 3 , corners 3 new Vector3( Mathf.Cos((up rot) Mathf.Deg2Rad) rect.rect.width, Mathf.Sin((up rot) Mathf.Deg2Rad) rect.rect.height))
|
0 |
Unity Renderer "raycasts" from top down? I'm trying to have objects in a game be selectable only from a top down orthographic camera view. I think having physics colliders might be overkill for that especially because this only needs to be in 2D and not 3D. Is there another method that might be better, such as something like a renderer quot raycasts quot , but perhaps even more performant as it is just from the orthographic 2D top down view
|
0 |
Avoiding overlapping UI Images When an enemy dies in my game, it drops an item on the ground. Enemies may drop multiple items. Currently, the item will always drop a set distance directly below the origin of the enemy when it dies. Therefore, if multiple items are dropped, I only see the most recently dropped item on the ground. Moreover, each item has a UI label clamped to some offset distance above the item. As such, I only see the UI label of the "most recently" dropped item. Because every item dropped by an enemy drops at the same physical location, and because I haven't added code to deal with this kind of thing, the physical game objects overlap with each other and the UI labels of those items overlap with each other. My question is pretty general. What are the best ways to modify my code such that 1) If multiple items are dropped, there will appear to be multiple game objects on the ground (Close enough to the origin)? 2) The UI labels attached to each item will appear as close as possible to that item without overlapping with the other items' UI labels? I would appreciate direct assistance or references that deal with this kind of thing. Thanks.
|
0 |
Reading text from file changes the text? I'm currently trying to load a simple text file and filter it by a certain string. In the text file I'm using a new line for each value and sometimes use a " " to make things easier to read for me when viewing the .txt file. Now, when I load the file and split it by new lines I end up with a list of substrings, each representing a value I need. Plus, all the "seperators" I put into the file. My goal is to clean the list from all the seperators and basically just remove them from the list. However, RemoveAll does not work and I found out that the strings containing " " are not really " ", but something else, because using string.Equals(" ") fails on them. Somewhere when reading the data or splitting it, something happened to those parts, but I can't figure out what's happening. Here's the code void Awake() fileLines new List lt string gt () TextAsset txt Resources.Load lt TextAsset gt ("SubjectPages test") fileLines new List lt string gt () fileLines txt.text.Split(new string " n" , System.StringSplitOptions.None).ToList lt string gt () fileLines.RemoveAll(x gt ((string)x) "") fileLines.RemoveAll(x gt ((string)x) " ") for (int i 0 i lt fileLines.Count i ) Debug.Log( fileLines i " " ( fileLines i .Equals(" ")) " " ( fileLines i " ")) Removing empty lines with RemoveAll seems to work fine.
|
0 |
Is it better to load all of the scene at once or load small parts of it as the player moves? I want to create a lot of detail in my game but I don t want to kill the frame rate tracking all the models and movements (like all the grass). Will loading them in pieces save the frame rate or will constantly loading and unloading models with every step negate any benefits of loading in pieces? I want to only load what the player will see at that moment and nothing else until the player either moves the camera or walks. I also want to know if loading a scene on Unity uses the gpu or the cpu?
|
0 |
How to make a character that moves like a slinky? I have a school assignment to make a 2D platformer game, with a character that moves like a slinky (Animated example from the assignment linked above) At first, the character needs to grow in height over time When the player presses a button, the character starts to bend toward the next platform Its height when you press the button determines whether it will hit the next platform After that it must shrink to its initial size, and it goes over again. How can I approach this?
|
0 |
Sprite with shadows in both sides I have a gameobject with a SpriteRenderer, and I want it to cast (and receive) shadows like a 3D model. The sprite will turn around depending of his direction, so all faces must cast shadows. I already activated Cast Shadows and Receive Shadows in the Sprite Renderer component, and also included a Transparent Cutout shader with the Cull Off instruction (so all faces are drawn), but only one side of the sprite is being affected by light, while the other is even darker. To ilustrate How can I achieve an sprite casting shadows with both faces?
|
0 |
Cause a projectile to wait at the position initially fired for a second before flying off I want to have a projectile that the character fires stay in the same place for a second or two before flying off in the direction of the mouse at the initial time of fire. The character can move away from the projectile after firing it, and the projectile wont move till after the time has passed.
|
0 |
Unity How can I enlarge the sprite to avoid the movement of the character when the pivot change? Changing the pivot to custom on all of the sprites is not a viable option for me Video showing the problem https youtu.be YpAdamkbhFA
|
0 |
How can I avoid player see through the avatar? I'm creating a SteamVR HTC Vive game with Unity3D. I have a rigged avatar performing animations. Currently, if the player goes forward, it will see the moving eye balls and others inside the head. Since it's a small space, I can't allow him to step back to avoid the see through caused by the collision. What are other options to avoid it? I'm thinking about setting up two colliders, one on the animated model and the other on the head of the player, so it can trigger a 360 dark screen to warn the player. How should I create the dark screen for the warning?
|
0 |
How does Unity store references to GameObjects in a scene A Monobehaviour can have references to GameObjects in the same scene, but Prefabs, ScriptableObjects can't reference GameObjects in a scene. While Assets, Objects and serialization covers references to assets, i.e. actual files, it doesn't explain how references to scene objects work. But it has to be some kind of serialization, for example, do they also consist of a GUID part and a local id part when serialized?
|
0 |
What is "Avatar" in the "Animation Controller" used for? I'm using animation layers for a model of type quot Generic quot . The quot Base quot layer contains an quot Idle quot animation. The quot Shooting Layer quot contains a pistol shooting animation. I want the shooting layer animation to only affect the upper body. To do that, I need to use an Avatar Mask, I think. In the avatar mask, I have to select if I want it to be of type quot Humanoid quot or of type quot Generic quot . I will not use a quot Humanoid quot avatar mask because my animations are perfectly tailored for my model, and I don't need any retargetting. Instead, I wanted to use the quot Transform quot avatar mask type. However, it seems to expect an avatar However, I haven't had the need to create one yet. Do I really need to create an avatar? I don't want any quot Humanoid quot , I want to have full control over my animations and over what's going on. I have tried quot Humanoid quot before, and for me, it's a total loss of control as I can no longer tell what is a bug mis use by me and what is automatic retargetting done by Unity, so I want to avoid it by any means. Why do I have to create an quot avatar quot ? What is it actually? Unity already has my generic model to work with, so it knows the transform. Why does it want an quot avatar quot ? Edit The strange thing is I can create an avatar the usual way gt quot Rig gt Create Avatar quot gt quot From this model quot . Then I have an avatar. In the avatar mask, I need to feed an avatar. I do this, then it shows my transform. Now I can delete the avatar, and it still remembers my transform. Strange... not sure why Unity can't simply use the transform.
|
0 |
Why every character I drag to timeline is disabled in the timeline? I dragged 3 different characters to the timeline window and each one asked for track so I did animation track for all of them but on each track on the left side there is a yellow triangle say "The component is disabled" I created cinemachine virtual camera and it added the brain component to the main camera and created a timeline automatic for the virtual camera but when dragging a character to the timeline window I'm getting this yellow triangle with the message it's disabled. You can see in the screenshot on the left side in the timeline window the yellow triangles with the message.
|
0 |
What is the process to start developing games for the PS Vita? Let's assume a solo indie developer using Unity and targetting the PS Vita. Let's also assume that the developer's region is Europe. What does the developer need to start developing (only developing, not publishing) on the PS Vita? Which Unity version license? What needs to be done on the Playstation side? (registration etc) As an extra point What extra steps are needed for the said developer be able to distribute an alpha beta version of the game? (for a gamejam and feedback)
|
0 |
Player motion and combo systems Where do you usually implement player motion when going through the state machine of a combo system? An example, when player presses X Y it must do an uppercut like movement (Like street fighter) where the player jumps and hits. Another example could be the Devil may cry series where you can press down sword button and the enemy is thrown up and the player authomatically jumps to let player hit target in the air. When creating a combo, you have 2 things to take care of. One is the media that will be played when the combo is done (sound, animation, etc...) and the other the movement of the player when doing this combo. How do you handle the movement of the player? I have 2 posible options 1) Include the player motion (translation, rotatio, etc...) in the animation 2) Delegate the player motion to the combo nodes while they are being linked. First option could be the easiest but seems a bit restrictive. For example if you want to let the player do some other action while the current combo node media is playing (ej. jumping) could be tricky (Jump hit). Second option would need to have some many diffeernt nodes (We could use some kind of delegates here to minimize the node count(IOC)) to cover all the motion needs of every part of the combo. What do you think. Am I thinking too much? Cheers.
|
0 |
Is there any way of creating primitive 2D shapes in unity? I have read the whole unity manual and watched the videos on sprites but I have a question. Is there any way of creating primitive 2D shapes in unity? (I will be assigning trigger colliders to these as well). Or does one need to have a 3rd party program even for basic primitive 2D shapes? My game really is very minimalist. I did think about using particle system in a clever way but that won't have triggers and may not be as memory efficient for the several basic shapes that I am after.
|
0 |
Connecting varying tilemap layouts at possible connection points? I'm building an isometric 3D ARPG in Unity3D, and I have a tilemap, for example a dungeon. I have tiles marked where a door could be placed. I select a random "could be a door" tile from the tilemap. I "receive" an any shaped room, which could be a prefab, or a generated one as well. This room got tiles marked for door placement as well. Without editing anything how could I easily determine whether this room could be connected to the existing dungeon via the selected connection point? (and of course find the solution if it could be) by (valid) connecting I mean only their doors and walls can overlap, but nothing else. (and removing the duplicates, creating the door itself, etc) (Of course rooms can differ from rectangles)
|
0 |
Unity LWRP alternatives for camera stacking I am working on upgrading a project in unity from a 2018 version to the latest 2019. One of the mechanics of the game is an AR (augmented reality) system. Some of the UI elements appear in the 3D world, but clearly as part of the hud. They need to be transformed as the camera moves, but should always be drawn on top of the 3d scene. The old project achieved this via camera stacking. All the AR elements were drawn on a different camera which rendered on top of the 3D camera. The clear flags were set to "depth only" and it removed all other elements from that camera. In the 2019 version of Unity with the Lightweight Render Pipeline (LWRP), the clear flags feature on the camera is missing. To the best of my research, camera stacking has been removed from LWRP. What are my alternatives? How can I now achieve this effect? I would like to stick to LWRP as I am using Shader Graph for many of the effects in the game.
|
0 |
How do I get a reference to a component on a sibling object in C Script? I'm working on a game, where the player dumps trash from Trash cans into a Trash Truck. These Trash cans have a random chance of having a Racoon on top of them. I have a script set up to detect when the player enters a Collider Trigger attached to the Racoon, which will cause it to play an animation and start attacking the player. To do that, it needs to work with a racoon navigation component on a neighbouring object I'm trying to access the RacoonNAVAI component on the Racoon Mover game object with this line racNav transform.parent.parent.Find( quot Racoon Mover quot ).gameObject.GetComponent lt RacoonNAVAI gt () But it's throwing a null reference exception. How can I correctly get a reference to this component?
|
0 |
How to iterate over 25 Sprite Objects (Unity 5 C ) I wanna show a minimap on the screen. The minimap would look like this (bottom right corner, this was done time ago in Visual Studio) Have two problems with that, I have 25 Image objects created in the scene and 25 in the playercontroller script public Image minimap0, minimap1, minimap2, minimap3, ... , minimap24 but I can't make to change its sprite, and also, I don't know how to change all 25 objects sprite with a "for" loop (the foor will look like this http imgur.com qfi1Ht1 ). The map is stored in an array for checking positions.
|
0 |
Can't reference my custom editor script from a non editor script even when using its namespace I know that certain namespaces are necessary to include to specify under what scope certain methods are found, and this also saves typing. Otherwise the error CS0246 is thrown if referencing an unknown type. The problem is, that I am using a namespace in a script in Assets Scripts And that namespace is defined in a script in Editors Data AnotherFile So I am getting an error CS0246. How could I solve this without moving that script into the Assets Scripts location? SCRIPT LOCATED IN EDITOR DATA ANOTHERFILE using System.Collections.Generic using UnityEngine using UnityEditor namespace NodeEditorWindow CreateAssetMenu public class LevelFlowData BaseNodeEditorData lt BaseLevelNode, LevelFlowEditorAttributes gt private const string MENU ITEM PATH "Create ScriptableObjects LevelFlowData" private const string NEW ASSET PATH "ScriptableObjects Level Flow Data" SerializeField private string name lt summary gt Gets and Sets name property. lt summary gt public string name get return name set name value MenuItem(MENU ITEM PATH) public static void CreateAsset() LevelFlowData scriptableObject ScriptableObject.CreateInstance lt LevelFlowData gt () as LevelFlowData AssetDatabase.CreateAsset(scriptableObject, AssetDatabase.GenerateUniqueAssetPath(NEW ASSET PATH)) SCRIPT LOCATED ON ASSETS SCRIPTS ... using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using GameData using NodeEditorWindow HERE I AM USINGTHE OTHER CLASS'S NAMESPACE public class LevelController Singleton lt LevelController gt Header("Level Data ") SerializeField private LevelFlowData levelFlowData These are the errors I get in console (both CS0246) Assets Scripts Scene Controllers LevelController.cs(6,7) error CS0246 The type or namespace name NodeEditorWindow' could not be found. Are you missing an assembly reference? Assets Scripts Scene Controllers LevelController.cs(11,27) error CS0246 The type or namespace name LevelFlowData' could not be found. Are you missing an assembly reference? Sorry if this seems to be a repeated question, but I haven't found any solution to this error due to having scripts on different paths (but using the namespaces). Thanks in advance.
|
0 |
Remove sprite reference before build in Unity All the the characters in my 2D game have SpriteRenderers to animate the characters. Some of the characters are only active in their scenes sometimes, so I load their sprites asynchronously based on game state. During edit mode, I have at least one sprite from an animation assigned to each sprite renderer so I can tell where the game object is. The problem is that including even a single sprite will load up the entire sprite atlas at runtime if I allow the SpriteRenderer.sprite to be set. Is there an efficient way to unset the SpriteRenderer.sprite for a build, but not during edit time? Is there a better way to handle this?
|
0 |
Unity 2D Bullet AddForce does not work I got the following code public ParticleSystem PS public GameObject origin public float thrust 1.0f public GameObject bullet private GameObject bullet Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetMouseButtonDown(0)) Debug.Log("Pressed left click.") PS.Play() bullet Instantiate(bullet, origin.transform.position, origin.transform.rotation) bullet.GetComponent lt Rigidbody2D gt ().AddForce(origin.transform.forward thrust) Where everything is working except the AddForce, the bullet is just dropping out of my weapon. I've made some research and my script seems to be correct. The bullet has attached a circle collider and a rigidbody2D. Update This did not change anything bullet.GetComponent lt Rigidbody2D gt ().AddForce(origin.transform.forward thrust, ForceMode2D.Impulse) And this neither bullet.GetComponent lt Rigidbody2D gt ().velocity origin.transform.forward thrust It's weird, because all of these should work actually.
|
0 |
Shadows in Android using Unity 5 The point lights in my scene cast shadows when it's in the editor mode but the light passes through walls in the build or play mode. I checked the quality settings and set it to hard and soft shadows for all quality settings but that didn't fix it. It does work when I increase the quality when I build it for Standalone but not when I build for Android. I've removed the dx11 option in the PC Mac Standalone settings. I've changed both forward and deferred rendering options. I'm testing it on a Moto G 1st Gen XT 1033 .
|
0 |
Size of .skp gets doubled after importing to Unity I have created a 3D model in SketchUp, and it is about 1.6Mb in size. After importing it to Unity, the size more than doubled to 4Mb. Why is that?
|
0 |
Problem with camera deapth culling only option and objects in front of each other I have a prefab with 2 cameras. the 1st is rendering the world, the 2nd one all the suff in front of the 1st person characters "face". Now i have a problem with a gun using a muzzleflash both on the deapth only camera. The muzzleflash is on the very front tip of the gun and i assume because the 2nd face camera is set to "deapth only" it causes the muzzleflash to be off place. I came up with 3 ideas 1 changing the layer of the muzzleflash to world for some frames everytime a muzzleflash appears 2 having a 3rd camera rendering the muzzleflash only 3 adjusting the gun on the face camera, the muzzleflash on the world camera I assume the 1st two options have a huge overload, i prefer the 3rd one. But is it a good way to do it? How should i proceed in this situation? Or how do others? I also have animations so it can appear on 2 positions, normal and scoped. Edit Here is an image i added Debug.Break() as it was instantiated, its totally correct aligned.
|
0 |
Subclasses in unity editor I would like to implement an action system where gameobjects offer different actions available to characters. Actions are composed of several steps holding the details to be performed. These steps have different logic applied to them (go to location, play animation for a time, change variables), so I would like to have them as subclasses. However I would also like to be able to set up the actual data for an action in the UnityEditor. I know it is possible to do this using ScriptableObjects, but that requires creating an asset for each instance of a step, which I'd like to avoid, since only the classes get reused, the instances being pretty much unique to each gameobject. Is there a way to work with subclasses in the unityeditor without requiring a dedicated asset for each of the subclass instances cluttering up my folders?
|
0 |
Blood covering ground in Unity 2D platformer I have just started my adventure with Unity so my question may seem silly to experienced users but anyway I'll give it a try. If you could just give me couple of keywords I could search for in order to solve my problem I would be very grateful. As a sample project I wanted to create 2D pixel platformer, something like Contra. All went well up to the moment when I wanted to add some blood dripping from my enemies. I got stuck on generating the blood particles and simulating them painting over the ground. The effect I want to achieve looks like this (live example http jsfiddle.net 0pg0LpL1 4 embedded result , animated gif http imgur.com oTeDydV) I am wondering what is the best approach to achieve such effect. I thought about generating the texture of blood stains on the fly and placing it before camera. It would look like this scene lt blood texture lt camera. The blood texture would be generated from lines drawn by "flying" blood particles masked by the ground platforms texture Blood particle traces http imgur.com a 0iIeQ Ground mask http imgur.com a YKvCK Masked traces (what I call blood texture) http imgur.com a M8z2v What is the best approach to achieve such effect? I know that generating texture with Texture2D.SetPixels on each frame is not optimal. I also see challenge in having a blood texture large enough to span over entire level to keep memory of all the blood spilled. Also the solution with one blood texture will not work if I wanted to have moving platforms that should also be painted. Thanks in advance for any suggestions.
|
0 |
Unity Rotations Not Following Local Nor Global Axis? In the gif below, you can see that rotating on X moves all 3 axis including the X axis. It's possible it's rotating on the global X rather than local X (hard to tell). But Y looks more like it's rotating on global Z and Z is quite clearly rotating on local Z. What is going on? Why is there no consistency?
|
0 |
Collision between Mesh Plane and 2D Sprite I've just recently started programming using Unity and made a couple of games with it, I'm trying out more and more advanced stuff as I do more games, but right now... I'm trying to make a game that's basically a way simpler clone of pokemon y r g b (I'm only concerned about tile placement, player movement collision, and dialogue boxes at this time) I tried about 3 methods for tile placement and found that using a mesh worked best for me (using tiled and tiled2unity) and imported the tmx files into unity. Now, I just dont know where to go from here. Starting with the player, I don't want to add physics since most games like this doesn't really have physics involved. So I tried adding a box collider to the player then a controller that uses transform.translate. Unfortunately, I dont think the colliders work nicely with transform.translate. In this scenario, is the best setup for the player simply just using a kinematic rigidbody2d then adding the code methods to collide with the map? Also since translate might be a bad idea, is transform.position a better alternative to use? (note that the player moves in increments in a "tile like movement", any comments or suggestions?) I'm also quite surprised by the lack of simpler games such as this one. Most of the examples I can find online are physics based platformers and top downs that use code like velocity, addForce, with physics components involved. Any available source code that I could study would be welcome. (I've also posted this on Unity Forums but people frequent here more often)
|
0 |
Unity 2D Problem with player running ON wall instead of falling I m having a problem with my game (yes, I'm new with Unity). I'm trying to make a simple 2d platformer and I ran into this situation Youtube Link As you can see, when the player hits the BoxCollider from the side, it tries to get a hold of it instead of just keep going down... These are the properties of my player And the block only has the default box collider. Any ideas? Thanks!
|
0 |
In Unity, How to format Old RPCs into new "PunRPCs" In older unity versions you could simply used RPC. With newer verisons of Unity my code now doesn't work and it says that it needs to be transformed into "PunRPC" , Pun being "Photon Unity Networking." I am not sure how to reformat it to work with current unity versions. Can anyone shed light on this? My Code FXManager.cs 1 using UnityEngine 2 using System.Collections 3 4 public class FXManager MonoBehaviour 5 6 RPC 7 void SniperBulletFX( Vector3 startPos, Vector3 endPos ) 8 Debug.Log ("SniperBulletFX") 9 10 11 PlayerShooting.cs 1 using UnityEngine 2 using System.Collections 3 4 public class PlayerShooting MonoBehaviour 5 6 public float fireRate 0.5f 7 float cooldown 0 8 public float damage 25f 9 FXManager fxManager 10 11 void Start() 12 fxManager GameObject.FindObjectOfType lt FXManager gt () 13 14 if(fxManager null) 15 Debug.LogError("Couldn't find a FXManger.") 16 17 18 19 20 Update is called once per frame 21 void Update () 22 cooldown Time.deltaTime 23 24 if (Input.GetButton ("Fire1")) 25 Player wants to shoot...so. Shoot. 26 Fire () 27 28 29 30 void Fire() 31 32 if (cooldown gt 0) 33 return 34 35 36 Debug.Log ("Firing our gun") 37 38 Ray ray new Ray (Camera.main.transform.position, Camera.main.transform.forward) 39 Transform hitTransform 40 Vector3 hitPoint 41 42 hitTransform FindClosestHitObject (ray, out hitPoint) 43 44 if (hitTransform ! null) 45 Debug.Log ("We hit " hitTransform.name) 46 47 We could do a special effect at the hit location 48 DoRicochetEffectAt (hitPoint) 49 50 Health h hitTransform.GetComponent lt Health gt () 51 52 while (h null amp amp hitTransform.parent) 53 hitTransform hitTransform.parent 54 h hitTransform.GetComponent lt Health gt () 55 56 57 Once we reach here, hitTransform may not be the hitTransform we started with! 58 59 if (h ! null) 60 This next line is the equivalent of calling 61 h.takeDamage( damage) 62 Except more "networky" 63 PhotonView pv h.GetComponent lt PhotonView gt () 64 if (pv null) 65 Debug.LogError ("Freak out!") 66 else 67 h.GetComponent lt PhotonView gt ().RPC ("TakeDamage", PhotonTargets.AllBuffered, damage) 68 69 70 71 if (fxManager ! null) 72 fxManager.GetComponent lt PhotonView gt ().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint) 73 74 75 else 76 We didn't hit anything (except empty space), but let's do a visual FX anyway 77 if (fxManager ! null) 78 hitPoint Camera.main.transform.position (Camera.main.transform.forward 100f) 79 fxManager.GetComponent lt PhotonView gt ().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint) 80 81 82 83 cooldown fireRate 84 If anymore information is needed, please let me know, I would love to figure out how the new "PunRPC(Photon Unity Neworking)" works so I can use it in future projects. Edit This is the error I get "PhotonView with ID 2 has no method "SniperBulletFx" marked with the PunRPC or PunRPC(JS) property! Args Vector3, Vector3 UnityEngine.Debug LogError(Object)"
|
0 |
How to stitch terrains together in Unity I'm building a world that consists of multiple terrains and I was wondering, how do I go about stitching them together so that features of my map will "fit" together? I know Unity has the SetNeighbors() method, but it appears as though that simply tells each terrain which terrain is next to the other. What I'm trying to accomplish is having multiple terrains and being able to have something like a mountain range move from one terrain to another and make it appear as though it's all one terrain.
|
0 |
How to throw a ball vive controller object in unity3d I have this simple line of code that through the ball. Under arm throw is right while if i try through any else ways its through movement is weird like a curve from down to up. what i am doing wrong. how do i through the ball using controller (touchingObject) object direction correctly realistically. Additionally i am also encounter a problem that if i through one ball all the previous throw balls move in that direction also. what the heck is that? gameObject.GetComponent lt Rigidbody gt ().AddForce(touchingObject.transform.forward 1000)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.