_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Coroutine not working (Unity) I made this code because I needed an image to display a couple seconds after an enemy spawns, but for some reason I can't make it work. There's no error in the console, but it doesn't display the image and I don't know what to do. Here's my script (it's attached to the enemy prefab) public class enemyAttack MonoBehaviour public float time 5f private IEnumerator coroutine public Image image private float t 5f void Start () image.gameObject.SetActive (false) image.enabled false coroutine nombredeCorutina (time, image) StartCoroutine (coroutine) private IEnumerator nombredeCorutina (float t, Image im) image.enabled true im.gameObject.SetActive (true) yield return new WaitForSeconds (t) coroutine nombredeCorutina (time, im) StartCoroutine (coroutine)
|
0 |
Using UDP vs Websockets I am running a Unity Game on a PC (for development purposes) and then on an Android phone (for production). I need to send data to the Game continuously from a WiFi enabled microcontroller (Esp32). Is it better for me to use UDP or Websockets for data transfer? What are the pros and cons of each method? In this scenario, the game device will act as a mobile hotspot while the esp32 will connect to this hotspot.
|
0 |
Exporting WebGL For Mobile Browsers I was asked by a client to create a pretty simple 3D game that will be embedded on a website, a plain landing page that will contain the game and will be played on mobile devices. The game itself has no complexity whatsoever, not in the functional aspect and not in the lighting shaders aspect the basic functionality is a simple finger swipe in order to quot throw quot a ball. I have checked and concluded that opening a webGL game on mobile devices might cause issues and only high end devices can run the game smoothly. My question is Is there a go to solution or any solution in which I can develop the game on Unity and build it for webGL in a way that it will be compatible with mobile devices? Or my only option is to develop the game using plain JS?
|
0 |
Process for converting unity asset to scenekit scene resource Has anyone successfully figured out a method for converting a unity3d asset to a 3d SceneKit model scene? I imagine it would require exporting the asset into some third party file type, and then importing into scene kit. If you have any knowledge that can help me, would you kindly explain the process? Unity3d has a fantastic asset store, and I want to import some of these things to a project that requires scenekit (unfortunately, "just use unity" is not really an answer to my problem set).
|
0 |
Unity3D CrossPlatformInput StandardAsset Multitouch I have a small game I am working on, and I am trying to add touch support to it. Before I try to add that into the real game I wanted to do a test run on a small project. The project consists of a capsule to be the player, and the application accepts movement from a on screen joystick, and accepts a button click from a UI button. The button triggers the attack, and the joystick triggers the movement. Both of these controls work as designed but they will not work together, meaning I can do one or the other. I was hoping to use the standard asset as to not re invent the wheel for speed... below is the code that "Should" be triggering when both controls are used, just as a note this same code works when I use mouse and keyboard together so this is something to do with the mobile stuff.. using UnityEngine using System.Collections using UnityStandardAssets.CrossPlatformInput public class PlayerController MonoBehaviour public float playerSpeed 10f Transform weapon Use this for initialization void Start () weapon transform.FindChild("Weapon") Update is called once per frame void Update () DirectionalMovements() ButtonPresses() void ButtonPresses() if (CrossPlatformInputManager.GetButtonDown("Fire1")) weapon.GetComponent lt Sword gt ().AttackOne() void DirectionalMovements() float moveVertical CrossPlatformInputManager.GetAxis("Vertical") playerSpeed Time.deltaTime float moveHorizontal CrossPlatformInputManager.GetAxis("Horizontal") playerSpeed Time.deltaTime Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) transform.Translate(movement, Space.World) if (movement ! Vector3.zero) transform.rotation Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement.normalized), playerSpeed) Any thoughts would be greatly appreciated.. I just do not see why both controls are not picked up here.
|
0 |
Where's Anti Aliasing in LWRP? In Unity 2019.2 LWRP (lightweight render pipeline project) the default Game Output(Quality High) is rendering with jaggies. Inorder to get a clear render ,while looking for the Anti Aliasing option it doesn't seem to be under the default location (Edit Project settings Quality )for LWRP projects. Where is the Anti Aliasing option in LWRP and is there any other way to get a clear game render?
|
0 |
Get the object that triggered the event I am trying to make a simple tooltip for my game. I added event trigger to object that I want to trigger an event on mouse hover (PointerEnter). And I want to get the game object that triggered the event in ShowTooltip(). I tried requiring BaseEventData in the void but it gave me error. void ShowTooltip(BaseEventData baseEvent) Debug.Log(baseEvent.selectedObject.name) The error Failed to call function ShowTooltip of class UIManager Calling function ShowTooltip with no parameters but the function requires 1.
|
0 |
How to change a variable in the spawnpoint from another prefab I refer the website for proper way of referencing the script How to call a public function from another script in Unity? but it does not work, still return a nullreference exception in the example below. Not sure how to fix it.Apart from that I also consider using int a public int A get set and in HPscript using spawnpoint.A spawnpoint.A 1 but it come out the content is for read only. Below is the codes I using. I attach this code to a capsule gameobject that is use to spawn prefab gameobject,drag and drop prefab to the enemy GameObject inspector window, this part working correctly. using System using UnityEngine public class Spawnpoint MonoBehaviour public GameObject Enemy public int a int currentstate 0 int previousstate 0 void Counting() the below if statement is to ensure the Gameobject only spawn once when condition become true in every 10seconds var d DateTime.Now.Second 10 if(d 0) currentstate 1 else currentstate 0 void Spawn() Stop spawning when Gameobject equal 5 if (d 0 amp amp currentstate! previousstate) if(a lt 5) Instantiate(Enemy, new Vector3(UnityEngine.Random.Range(0, 4), 1, UnityEngine.Random.Range(0, 4)),Quaternion.identity) a a 1 void Update() Counting() Spawn() previousstate currentstate The script below is not working. I want the HPscript to deduct the value quot a quot ,in Spawnpoint script so the script will continue spawn enemy when number less than 5.This script is attached to the prefab gameobject that is place in asset folder. using System using UnityEngine public class HPScript MonoBehaviour Spawnpoint spawnpoint void Start() spawnpoint GetComponent lt Spawnpoint gt () public void counting() var c DateTime.Now.Second 30 if(c 0) spawnpoint.a spawnpoint.a 1 Destroy(gameObject) void Update() counting()
|
0 |
How I can count how many time gameOver scene is loaded? I'm building a game using unity 3d and I want to add an interstitial ads to it, but I want it to appear after the player lost every 3 times. So when the player loses for the first time the ads will appear, and when he loses for the second and third time, nothing appears until he lost for fourth time.
|
0 |
Unity Ragdoll Colliders don't collide I have a humanoid character with Ragdoll setup in Unity. However the box capsule colliders on the various parts of the body don't collide with other static geometry. They do collide with the ground but not with any other static meshes. Is it possible to use them as colliders towards static meshes and what do I need to do for it to work?
|
0 |
What is the best way to increase slowly object movement speed and slow down the object near the end? There a Lerp but also SmoothDamp. In this script I'm using SmoothDamp but why not using Lerp ? And how should I use this script with the SmoothDamp tp make slowly increasing speed at the start ? Now it's only slow down at the end but I want it also to increase slowly at the start and then slowly down near the end. using System.Collections using System.Collections.Generic using UnityEngine public class MovementSpeedController MonoBehaviour public Transform target private Vector3 velocity Vector3.zero public float smoothTime 0.3F void Update() transform.position Vector3.SmoothDamp(transform.position, target.position, ref velocity, smoothTime)
|
0 |
Blender FBX exports to Unity3D have incomplete animation sequences Using Blender, I have rigged and animated this model with this attack action. I exported this model to an FBX format and imported the said FBX file into my Unity3D project. However, when I imported it, I noticed that the animation sequence is incomplete As you can see, the sword does not animate correctly and remains unmoved in its original position. In Blender, the sword and scabbard are animated in Pose mode with IK and other constraints. However, as I understand it, FBX bakes these constraints into the animation, so I'm not sure if that causes the issue. Why is the sword not animating correctly? How do I fix this so that the Unity animation is 100 faithful to the Blender animation?
|
0 |
Run some objc code very early in unity iOS game lifetime I want to hook up a crash reporting service to my unity iOS game. It's just one line of objC to add, as early into the app lifecycle as possible, but I'm not sure how to get it to run. I know I could make a native plugin and then call that from some Awake() function in C , but that's too late for my purposes. I'm not a native iOS developer, but I know enough to be dangerous. I have been able to google enough that I know I want something to with UnityAppController, probably preStartUnity(). But that's all. Has anyone got further resources on how to do this? Or another way, if I'm barking up the wrong tree? edit I'm on unity 4.6.
|
0 |
Why do not Easy Mobile Pro scripts know about each other? I am getting this error when I try to build the project Assets EasyMobile Scripts Modules NativeAPIs NativeUI Nati veUI AlertPopup.cs(68,17) error CS0103 The name 'AndroidNativeAlert' does not exist in the current context I tried adding this to my NativeUI AlertPopup.cs if UNITY ANDROID using EasyMobile.Internal.StoreReview.Android endif Hint says unnecessary using. Googling, searching Unity EMP forum and thread did not bring any results. Unity version 2019.2 .net 4.x EMP 2.5 If I try adding a breakpoint it says The breakpoint will not currently be hit. Unable to find a corresponding location. AndroidNativeAlert is a static class, have have no clue why it can't been seen from the other one.
|
0 |
How can I set only the players X rotation to 0 in Quaternion.Slerp in Unity? I want to set the players X axis to zero while he is turning to the target Object but I dont get it to work. Code public float rotationSpeed void OnMouseDown() PLAYER ROTATION TO ORE OBJECT var rotation Quaternion.LookRotation(transform.position player.transform.position) player.transform.rotation Quaternion.Slerp (player.transform.rotation, rotation, rotationSpeed Time.deltaTime)
|
0 |
How do I get a Light's Range value in Shader? I'm trying to write a simple frag vert shader that, depending on whether it is in the range of a light, will paint the appropriate colour from either the 'lit' texture or from the 'unlit' texture. Therefore, I need to compare the distance between the light to the range of the light. I've been googling all kinds of things, but I can't seem to find a way of accessing the range value of the light. Is there a way to do so? If not, is there some kind of derived data I could use as an alternative? I was able to find this method here, which seems to be the most promising so far, however after playing around for a bit, I still can't seem to get what I need. There's some talk about LightMatrix0 not being populated. Can anyone confirm? I've also had it suggested to use SetFloat() and pass in the range like that...however, that provides no easy way of telling one light apart from another short of using the light's position as a key. As several key lights in the game will be moving this is just ugly and inefficient. Update I found the variable unity LightAtten in the Unity Shader Variables documentation. However, this is only used for Vertex Lit shading, which isn't exactly ideal, especially considering the lack of console support. Could there be a way to pipe this variable to Forward Rendering? Update 2 For clarification, shading should otherwise be 'flat' (ie no need for diffuse etc) Also, what I've currently got (albeit, not currently working as desired and currently using a workaround) Shader "Lantern Flat Pullup" Properties LitTex ("Lit (RGB)", 2D) "white" UnlitTex ("Unlit (RGB)", 2D) "white" Falloff ("Falloff", 2D) "white" Pullup ("Pull up Point", Range(0,1)) 0.7 SubShader Pass Tags "LightMode" "ForwardBase" LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform sampler2D UnlitTex uniform float4 UnlitTex ST uniform sampler2D LitTex uniform float4 LitTex ST uniform float Pullup uniform float4 LightColor0 struct VI float4 vertex POSITION float4 tex TEXCOORD0 struct V2F float4 pos SV POSITION float4 tex TEXCOORD0 float4 posWorld TEXCOORD1 V2F vert(VI v) V2F o o.pos mul(UNITY MATRIX MVP, v.vertex) o.tex v.tex o.posWorld mul( Object2World, v.vertex) return o float4 frag(V2F i) COLOR float3 flatReflection LightColor0.xyz (1 length( WorldSpaceLightPos0.xyz i.posWorld.xyz)) float4 color Improve for light color etc if(length(flatReflection) gt Pullup) color tex2D( LitTex, i.tex.xy LitTex ST.xy LitTex ST.zw) else color tex2D( UnlitTex, i.tex.xy UnlitTex ST.xy UnlitTex ST.zw) return color ENDCG FallBack "Diffuse"
|
0 |
How to share image in persistentDataPath to facebook feed? I'm trying to share an image taking from CaptureScreenshot() using FB.ShareLink(...) to Facebook. My code is the following (After calling FB.Init(), etc..) string tmpScreenshotPathname "file " currentScreenshotPathname System.Uri contentUri new System.UriBuilder(tmpScreenshotPathname).Uri System.Uri imageUri new System.UriBuilder(tmpScreenshotPathname).Uri FB.ShareLink(contentUri, "Test", "Test desc", imageUri) However, when open the FB share, the page opens for a split second before returning me back to the game. I tried using a normal Uri such as http ........jpg and it works fine, but when I try to use a local Uri, it fails. Is there any way to share the image to the feed without uploading it to the user's Facebook gallery using FB.API? Because there's the case where the user might decide not to share the image to the feed.. but it would have already been uploaded to his gallery from FB.API.
|
0 |
Unity crashes when opening a project Why does this happen? I'm new to Unity development. I have installed Unity yesterday (2015 09 06). This is the error that I get
|
0 |
How to perform some custom math between the model matrix and the projection matrix? I'm trying to write a shader in Unity that will perform some custom math after the model view matrix is applied but before the projection matrix is applied. First off, I'm not sure whether I should be using a surface shader or an unlit shader. My impression is that a surface shader can do everything I need it to and the outcome will look better with less effort, is that right? I'm thinking that what I can do is manually apply the model and view matrices in the vertex shader, and then I have to tell it somehow to only apply the projection matrix in the rasterization step. Any idea how to go about this, or a different way to achieve the same result?
|
0 |
How to avoid assigning the same GameObject individually for every prefab? In many times, prefabs that share the same script may require the same GameObject in the script. For example, in my game I want to make a series of card prefabs. Each card has their own image when shown, but has the same back image when hidden. My script for card is public class DraggingCard DragAndDropItem public Sprite secretSprite This is the same for every card Sprite oringinalSprite This is individual for every card Image image public void Awake() image GetComponent lt Image gt () oringinalSprite image.sprite public void Activate() image.sprite oringinalSprite public void Hide() image.sprite secretSprite But if I write this, I'll have to assign the secretSprite in the inspector for every DraggingCard prefab. I tried to set secretPrefab to be static or const but neither worked. I believe there must be a clever way to avoid the repeat work. Could anyone tell me that? Thank you!
|
0 |
UnityWebRequest security I have a game where I would like to register users and post the outcome of matches between two users through web requests in Unity but have some security questions regarding UnityWebRequest. Assume the following code for sending a web request public class TestHTTP MonoBehaviour SerializeField private bool sendRequest false Update is called once per frame void Update() if (sendRequest) Model testModel new Model() testModel.ID quot 0001 quot testModel.name quot Random Name quot testModel.int1 555 StartCoroutine(SendWebRequest(testModel)) sendRequest false public IEnumerator SendWebRequest(Model m) string json JsonUtility.ToJson(m) string text JsonUtility.ToJson(SimpleAESEncryption.Encrypt(json, quot some password quot )) using (UnityWebRequest request UnityWebRequest.Post( quot some https quot , json)) request.method UnityWebRequest.kHttpVerbPOST request.SetRequestHeader( quot Content Type quot , quot application json quot ) yield return request.SendWebRequest() if (request.isNetworkError) Debug.Log( quot NETWORK ERROR quot request.error) else if (request.isHttpError) Debug.Log( quot HTTP ERROR quot request.error) else string returnData request.downloadHandler.text After doing a bit of testing I noted that sending via http would give a plain text body, which was remedied by switching to a https target. Is this enough of a level of encryption or should I add a layer of encryption for the model prior to sending? Lets assume my model contains data regarding the outcome of a match between two players. Would https (TLS 1.2) be enough to stop someone resending the same request packet to inflate their number of wins for example? Or should additional measures be taken to stop this?
|
0 |
Why doesn't my material show up on my imported model (Unity Blender) UPDATE The material does work on smaller objects like a simple sphere, but not on my big arena model, which is actually imported from blender, any suggestions? UPDATE Tried to export as .fbx, but doesn't change anything. I've imported this material pack https www.assetstore.unity3d.com en ! content 13004 I tried to apply it to my mesh, but only weird things happen, I can't see the texture at all. So I tried to apply this material in the "shader calibration scene" and that worked without any problem, even updating to the standard shader worked fine. So I tried to fix it with the following things Rebaking lighting Restarting Unity Tweaking the material settings Tweaking quality settings in Unity Building the project All these things couldn't fix it, but it should most likely be related to my project settings, since this material is working in another project (shader calibration) Here are my quality settings I'm not sure, which information is needed to answer the question, but I can provide it if you ask for it. Update with Object properties
|
0 |
Replacing all objects in scene with another object I have around 100 objects (prefab A) in my scene, all in different positions. Is it possible to replace all of these objects with another object (prefab B), so that the prefab B objects are placed in the same position as the prefab A objects were? I want this done in the editor, not in game.
|
0 |
On changing a voxel, don't recombine everything again, only modify the changed parts? I'm working on a voxel based game, where destructible structures are made out of cubes. (Some of them has 3000 voxels) I solved the framerate issues by combining them, but after making it able to handle multiple materials, calling the method causes a framerate drop. And it's annoying during runtime, because currently it recombines the whole structure when a voxel is changed (changed material, destroyed voxel, etc). One plan of mine is to decomposite the structures into smaller chunks, and only recombine the affected chunks instead of the whole structure. This increases drawcalls, but decreases framerate drops. By finding a good chunk size and chunk "making" heuristic, it would work I think. My other plan is to modify the combined mesh based on the affected voxels. For example when a voxel is destroyed, find its vertices in the combined mesh, and remove them. Or change those faces' material, etc. But I don't know how to do this. The bottleneck of my mesh combining algorithm is this private static Mesh CombineMeshes(MeshFilter meshFilters, List lt Material gt materials) Each material will have a mesh for it. var subMeshes new List lt Mesh gt () foreach (var material in materials) Make a combiner for each (sub)mesh that is mapped to the right material. var combiners new List lt CombineInstance gt () foreach (var meshFilter in meshFilters) The filter doesn't know what materials are involved, get the renderer. var renderer meshFilter.GetComponent lt MeshRenderer gt () lt (Easy optimization is possible here, give it a try!) Let's see if their materials are the one we want right now. var sharedMaterials renderer.sharedMaterials for (int i 0 i lt sharedMaterials.Length i ) var sharedMaterial sharedMaterials i if (sharedMaterial ! material sharedMaterial null) continue This submesh is the material we're looking for right now. CombineInstance ci new CombineInstance() ci.mesh meshFilter.sharedMesh ci.subMeshIndex 0 With zero it works with "i", every voxel in the structure will have every damagelayer. ci.transform meshFilter.transform.localToWorldMatrix combiners.Add(ci) Flatten into a single mesh. var mesh new Mesh() mesh.indexFormat UnityEngine.Rendering.IndexFormat.UInt32 mesh.CombineMeshes(combiners.ToArray(), true) subMeshes.Add(mesh) foreach (var meshFilter in meshFilters) meshFilter.GetComponent lt MeshRenderer gt ().enabled false The final mesh combine all the material specific meshes as independent submeshes. var finalCombiners new List lt CombineInstance gt () foreach (var mesh in subMeshes) CombineInstance ci new CombineInstance() ci.mesh mesh ci.subMeshIndex 0 ci.transform Matrix4x4.identity finalCombiners.Add(ci) var finalMesh new Mesh() finalMesh.indexFormat UnityEngine.Rendering.IndexFormat.UInt32 finalMesh.CombineMeshes(finalCombiners.ToArray(), false) return finalMesh Could you recommend something? Thanks!
|
0 |
Unity JSON parsing Array of Objects problem error JSON must represent an object type I'm trying to use Json to hold game dialog in a text asset file. I've tried to make a barebones project to test this and it is failing with the Error Message ArgumentException JSON must represent an object type. I have a class called LineData which has a few properties each line of dialog contains. In the Json there are just two lines for now. When I import and parse it to try and make a reference to one of the lines of dialog it fails. Here is all the code dialogJson.JSON "lineID" "BEDROOM DAVE 0001", "lineDialog" "Yaawwn, up i get for another fun packed day.", "lineDuration" 3 , "lineID" "BEDROOM DAVE 0002", "lineDialog" "Well I think I need a cigarette before I get to work!", "lineDuration" 3 LineData.cs using System Serializable public class LineData public string lineID public string lineDialog public float lineDuration GameController.cs using UnityEngine public class GameController MonoBehaviour TextAsset Dialog Data private void Start() Dialog Data Resources.Load lt TextAsset gt ("txt dialogJson") LineData line1 JsonUtility.FromJson lt LineData gt (Dialog Data.text) Debug.Log("line 1 dialog " line1.lineDialog) NOTE I read here (https answers.unity.com questions 1503047 json must represent an object type.html) that Unity "can't parse if the json consists of an array of objects". But I don't understand his explanation on how to get around this. Thanks EDIT I now have it without error, but the debug message is just empty didnt seem to get any data) . Here is the json now after the edits "LineData" "lineID" "BEDROOM DAVE 0001", "lineDialog" "Yaawwn, up i get for another fun packed day.", "lineDuration" 3 , "lineID" "BEDROOM DAVE 0002", "lineDialog" "Well I think I need a cigarette before I get to work!", "lineDuration" 3 I've also altered the GameController.cs like this (but now it says Index is outside array bounds public class GameController MonoBehaviour TextAsset Dialog Data private void Start() LineData lines new LineData 2 Dialog Data Resources.Load lt TextAsset gt ("txt dialogJson") lines JsonUtility.FromJson lt LineData gt (Dialog Data.text) Debug.Log("line 1 dialog " lines 0 .lineDialog)
|
0 |
How does Unity's Entity Component System Work In Practice? On the surface Entity Component seems like a good way to program games. Everything is a game object and those game objects are made up of components. The attraction is components are very flexible, just requiring you to "add" them to a game object to inherit it's functionality. So, obviously a good example might be a platform the character has to jump on. Maybe this thing has a collider, a moving component, maybe a rotating component, or maybe even a rigid "RotatingAndMovingPlatformComponent". Okay, that sounds great, just add all these components to the game object and that's it, you have this extra functionality. However, I find that this level of complexity is where it's usefulness ends. Try this with menus, complex character movement with multiple states, abstract ideas like game modes or game state, and your flexibility and modularity are destroyed. Menus involve a lot of specifics, complex character movement often involves many states meaning either communication between these components is needed or there must be a controlling component made just for this type of character. On top of this, some components will need to rely on game state in some way. I see very little benefit to programming this way over ordinary inheritance. The lack of object structures at compile time makes doing a lot of things very difficult and unreliable. I feel the best and easiest way of going about things would be using larger components with more dependencies. I don't see this as a problem ( more like unreal 4's architecture ), but then I wonder what's the point in the Entity Component architecture.
|
0 |
Assigning relative force to a projectile fired while orbiting a sphere Projectile Not Correctly Inheriting Parent Velocity (Unity3D) So I am trying to incorporate the above person's changes into a script I am making although I'm no great coder and I'm not even sure their solution works best for what I am doing. Essentially what I have right now is a high speed shooter where the player is being pushed around as a physics object on a sphere world rather than using translate for movement. I keep finding solutions that would work really well if I was just translating through xyz space. Using a physics object for my projectile has been working well (I can shoot in one direction and have the projectile hit my in the back after circling around) but once I get up to speed I'm in trouble. I think I've successfully incorporated the projectile portion into my script but currently it keeps shooting on the positive z axis. On top of that, I'm not even sure where to start incorporating the second half. Emitter Script using UnityEngine using System.Collections public class SpaceShoot MonoBehaviour public GameObject Bullet Emitter public GameObject Bullet public GameObject target Player public float Bullet Forward Force 100 public float Bullet Life 60 public float fireInterval 0.05f void Update() if (Input.GetKeyDown(KeyCode.Space)) InvokeRepeating("Fire", float.Epsilon, fireInterval) if (Input.GetKeyUp(KeyCode.Space)) CancelInvoke("Fire") void Fire() GameObject Temporary Bullet Handler Temporary Bullet Handler Instantiate(Bullet, Bullet Emitter.transform.position, Bullet Emitter.transform.rotation) as GameObject Rigidbody Temporary RigidBody Temporary RigidBody Temporary Bullet Handler.GetComponent lt Rigidbody gt () Temporary Bullet Handler.transform.Rotate(Vector3.left 90) Rigidbody target rigidbody target rigidbody target.GetComponent lt Rigidbody gt () Temporary RigidBody.velocity target rigidbody.velocity Temporary RigidBody.AddForce(transform.forward Bullet Forward Force) Destroy(Temporary Bullet Handler, Bullet Life) Edited script as it currently stands. It mostly does what I need although I'm trying to figure out a way to clamp the distance to the origin.
|
0 |
Sampling procedural texture generated in shader? We have a custom Unity surface shader which generates some procedural patterns. However we are getting very bad moire effects when the pattern frequency is too high (made worse by distance, surface angle). I would like to apply some kind of blur on the texture to reduce this moire effect. All of the shader blur examples I can find rely on sampling surrounding pixels from the texture bitmap. Since we've generated the pattern procedurally per pixel, such a bitmap doesn't exist. Does anyone know how we might introduce some kind of blur effect in this case, to reduce the moire? Thank you.
|
0 |
UI Button Click Animation We have animation states for Normal, Highlighted, Pressed and Disabled. How to set animation when a button is clicked?(after button released not pressed)? Thanks in advance
|
0 |
Classes in Unity internal vs public Why are classes created by the game developer in Unity public (by default) when you could just as easily make them internal? For example I go Assets Create C Script. Via the default script template, I have just created a public class that derives from MonoBehaviour. But technically shouldn't this class only have to be internal? If so, I really want to delete that public keyword, because having the word public is a slight distraction to me. Do outside DLLs call functions within the developer created DLL? I don't think so, right? Because the classes in other DLLs wouldn't know what funcitons are in there beforehand anyway. I don't know much about how these DLLs interact with each other, but I get the feeling outside DLLs don't particularly care about the one DLL assembly the game developer himself generates. Take a look at my picture it seems like Unity just jams all developer created scripts in one assembly. Yes, the assembly does reference MonoBehaviour, (so I assume other classes in all the other dlls are public, not internal) but no classes outside of this one need be concerned with the details inside this assembly. It doesn't matter that much. Yes, I could go on living my life peacefully and making my classes public within Unity. But is there any potential drawback, and isn't it considered better practice, to make them internal? If there's nothing wrong with making my classes internal, then I'm going to edit the default template.
|
0 |
Apply a special effect to a scene area My 2D game has a second camera on the scene that renders an upside down image of the scene and distorts it, giving the effect of water reflection. I render this camera first, and on top of it I render the main camera. This is working correctly as expected, however, I want to improve it's performance by performing this process in small sections of the scene instead of the whole screen. I created a trigger to detect which items should be turned upside down and rendered. How can I turn these items and distort them as I did with the whole scene, but only to the GameObjects detected inside the trigger? Note I can't assign them to a layer since the layer is already in use.
|
0 |
How do you handle aspect ratio differences with Unity 2D? I've gotten a lot of answers to this question, but they are all generic and generally not very useful. None of the tutorials talk about aspect ratio and dealing with mobile devices and there are a zillion ways to do it, all seem to have gotcha's and flaws. I really would love to know what successful games have used to handle different aspect ratios on iOS and Android without making a zillion different sized assets. I am strictly speaking mobile, not desktop, specifically with Unity and I don't care about the UI, I only care about the gameplay canvas. Issues I have in mind is when there are key things that have to be in certain places and cannot fall off the screen. Using black bars on top or bottom is unacceptable these days.
|
0 |
How to ensure Unity does not rearrange the sub meshes of a mesh on import? having a bit of a head scratcher problem here. I have my artist's making multiple unique meshes in Maya that contain 3 materials. Each material is assigned to a sub mesh in a specific order. This order is identical across all the meshes being created. When bringing over these meshes to Unity, we have noticed that some meshes keep their material sub mesh order from Maya, and some do not. It's been making code generated material swaps a nightmare. So a few questions 1.) What is Unity's logic when importing meshes and ordering the sub meshes? 2.) Is there a simple way to make sure Unity does NOT reorder the sub meshes material order? 3.) Is there a way on Maya's side when exporting to make sure the sub meshes material order is as intended? Any help or ideas is appreciated. Thanks!!
|
0 |
A shader that casts shadows, doesn't receive shadows and doesn't render any textures models at all? Bit of a strange one but I'm in the situation where i need a shader to essentially render nothing and cast a shadow! I found this though some googling but sadly that casts shadows onto itself which is undesirable.
|
0 |
Video feedback effect with recursive RenderTextures in Unity 2018.3 I have a project where I'm playing with a video feedback effect by rendering a camera to a RenderTexture and pointing the camera at a quad displaying that RenderTexture. This works great normally, but when trying out HDRP, LWRP, (and upgrading materials) or upgrading the entire project to 2018.3, the RenderTexture just stops working and shows black. I also tried with a completely new project and just had a camera, a quad, and a cube. That also didn't work. Is there any obvious reason this wouldn't be working? I spent a while trying out various settings but couldn't find anything that had any effect, so I really don't even know where to start.
|
0 |
Rotate perspective camera to align screen width to procedural object's width (Unity, C ) I give up. After much trying and searching, I have to say I was unable to achieve the following task, for which I must call for your wise advice. In my current Unity 5 application (using C ), there is a procedurally generated object (therefore with variable shape) to which the camera should be aligned when players hit a given key. By aligned, please understand it making the width of the screen parallel to the longest part of the object. The idea is represented in the following picture, where in black one can see the irregular object, in yellow is the bounding box. In other words, it means that I want the camera to be rotated so to align to the longest side of the object's bounding box. I tried that. Still, I was unable to properly calculate the correct angles so to rotate the camera in a way that the horizontal axis of the screen becomes parallel to the width of the objects' bounding box. Any help would be much appreciated.
|
0 |
What is the transformation order when using the Transform Class? I am currently using Unity 5.5 for the first time in a project and I've got some problems regarding transformations. I've got a background in more general 3D graphics meaning that I'm used to manually manage scene graphs and matrix transformation orders. My greatest problem when moving to Unity, and using their built in Transform Class, is that I can't find any information regarding the transformation order of rotation, localrotation, scaling, localscaling, position and localposition. I can't find any good information of this and It's driving me slightly mad. TL DR What's the transformation order of the Transform class?
|
0 |
How to move NavMesh Agent by animation? What's the best way to create a simple moving navmesh agent with animation? (e.g. a human enemy running to player) I have run animation that moves the enemy public void Run () animator.SetFloat ("Speed", 1f) but I am not sure how to combine it with navmesh. In one tutorial I saw Standard Assets ThirdPersonController .Move(...) used for that, but I am not sure if I should use it for that purpose, as I understand it was intended only for player characters? Or should I use animation that runs in place?
|
0 |
Plugins for creating and styling custom Editor Windows like C C Form Designer or Web Inspector ? Unity3d allows to construct window with custom UI. Just need to use EditorGUI EditorGUILayout classes and their static methods. Example of custom window The problem is that all the components have to be added manually via script. Then need to save, switch to Editor, wait for little compile things, and then we can see the result. In web development people use Web Inspector (for example, we can press F12 in chrome, Tab Elements Styles). We can add all needed properties to element and can see the result in real time. EDIT. another example (better than previous) we know C winFormApp, C MFC e.t.c, which has form designer. We can choose any elements and set their properties It would be nice to have similar plugins for Unity So. Does Unity3d have similar tools, utilities, plugins? Utilities to inspect code and editing styles (position, margin, padding, background, width, height, color e.t.c.)?
|
0 |
With a Texture Atlas that has 128x128 tiles, how can I use that in Unity3D? So I've got a working texture atlas that has tiles fitting 128x128. However, I can't quite figure out how to use them. I know it's probably got something to do with TileRenderer.material.SetTextureScale(" MainTex", new Vector2(0.25f, 0.25f)) TileRenderer.material.SetTextureOffset(" MainTex", new Vector2(0 0.25f,0)) but I'm not sure where to take it from there. Can anyone offer some advice? The size of the image is 1024x128 if that helps, which I think it might.
|
0 |
Why the rotation using the Coroutine is rotating but the object is in slant ? and how to rotate it with Coroutine non stop? using System.Collections using System.Collections.Generic using UnityEngine public class Spin MonoBehaviour public Vector3 targetRotation public float duration public bool spinInUpdate false Start is called before the first frame update void Start() if (spinInUpdate false) StartCoroutine(LerpFunction(Quaternion.Euler(targetRotation), duration)) Update is called once per frame void Update() if (spinInUpdate true) transform.Rotate(new Vector3(0, 1, 0)) IEnumerator LerpFunction(Quaternion endValue, float duration) float time 0 Quaternion startValue transform.rotation while (time lt duration) transform.rotation Quaternion.Lerp(startValue, endValue, time duration) time Time.deltaTime yield return null transform.rotation endValue slant I mean this is how it's rotating with the Coroutine the small cube that rotate is in slant When using the Update way it's rotating fine and this is how it should rotating also with the Coroutine for example on the X only The small cube when rotating either in update or in the Coroutine should not be slant. but it's slant in the Coroutine. And how can I add a speed factor to the Update to control the rotation in the Update in case using the Update ? About controlling the speed in the Update I just added a global float variable and in the Update transform.Rotate(new Vector3(0, Time.deltaTime rotationSpeed, 0)) and it's working for the speed.
|
0 |
How do you handle pathfinding for non tilemap 2d games? What methods do you use to handle path finding in non tiled 2D games? Tilemap based methods can use A and 3D has NavMesh available. The only success I ve had is with raycasts but it doesn t seem like a great way to handle things with hand draw sprites or uneven terrain.
|
0 |
Player object's model starts to shake after some time I created a default scene in a new project and imported a model from Unity's asset store and then get this strange behavior of the model starting to shake for no reason after some time after starting the game. I also have a script to read keyboard input and then apply forces to the model when the player presses some keys but the shaking of the model starts to happen even when the player does absolutely nothing. I'm really confused and have no idea where to look for a problem and google doesn't seem to have a solution to this either.
|
0 |
I prefer C C over Unity and other tools is it such a big downer for a game developer? We have a big game project using Unity at school. There are 12 of us working on it. My teacher seems to be convinced it's an important tool to teach students, since it makes students look from the high level to the lower level. I can understand his view, and I'm wondering Is unity such an important engine in game development companies? Are there a lot of companies using it because they can't afford to use something else? He is talking like Unity is a big player in game making, but I only see it fit small indie game companies who want to do a game as fast as possible. Do you think Unity is of that much importance in the industry? Does it endanger the value of C skills? It's not that I don't like Unity, it's just that I don't learn anything with it, I prefer to achieve little steps with Ogre or SFML instead. Also, we also have C practice exercises, but those are just practice with theory, nothing much.
|
0 |
Find out triangles that are not occluded from a camera view? For a project i need to find out triangles that are directly seen by the camera user. Triangles that are occluded by other triangles should be ignored. There may be 200 thousand triangles in a model, so raycasting on a CPU is no possibility due to performance. Is there something build in to unity or opengl that can do this? If not how would you approach this problem? Many 3d editing software use techniques, e. g. to select or slice only triangles that are visible.
|
0 |
Unity AudioClip lags when played My AudioClip is lagging when I play it in Unity3d. The AudioClip is supposed to play when you left click inside the game window. Steps I've tried for fixing it Uncompressing the .wav sound file. Setting the clip variable of an AudioSource to a clip and then playing the sound, but that's a different story. How the issue occurs When I start the game, on the first click it plays fine. But then after a few clicks, it starts slowing down and or lagging. This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI RequireComponent(typeof(AudioClip)) RequireComponent(typeof(AudioSource)) public class GameProcess MonoBehaviour public Canvas Game public AudioClip explosion AudioSource beatBox Transform btn Vector3 canvasMin Vector3 canvasMax Vector3 pointerMin Vector3 pointerMax Vector3 pointerPos void Start () btn Game.transform.FindChild("Pointer") canvasMin Game.GetComponent lt Collider gt ().bounds.min canvasMax Game.GetComponent lt Collider gt ().bounds.max pointerMin btn.GetComponent lt Collider gt ().bounds.min pointerMax btn.GetComponent lt Collider gt ().bounds.max beatBox GetComponent lt AudioSource gt () void Update () if (Input.GetMouseButton(0)) beatBox.PlayOneShot(explosion) if (!(pointerMin.x lt canvasMin.x) !(pointerMin.y lt canvasMin.y)) if(!(pointerMax.x gt canvasMax.x) !(pointerMax.y gt canvasMax.y)) btn.transform.position Input.mousePosition else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0) else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0)
|
0 |
Can I use trilinear filtering for my sprites, but keep their outlines unfiltered? Suppose that I have two images of equal size. They both contain a square https i.stack.imgur.com BI62X.png https i.stack.imgur.com Nev5Z.png When overlapped, both squares will appear next to each other. If both images use Point (no filter), they will contact without issues regardless of the amount of zoom or scale If you use either Bilinear or Trilinear, there will be an artifact visible in certain zoom scale levels Of course, that is to be expected from the very nature of the filters. As much as I would like to just leave it at Point (no filter), my game looks far better using Trilinear instead except of course, for the "borders" or points of contact. The ideal scenario for me as bizarre as it may sound, is to be able to use Trilinear filtering generally, but force the "outlines" of my sprites to stay as if they were Point (no filter). This way, my game looks painterly when zoomed in out (the game isn't pixel art), and I also avoid the "glitch" in specific contacts. Yes, the glitch is only noticeable if you use a scale zoom that is higher than 100 . Unfortunately, due to the nature of the game, the player should be able to zoom in out if they desire, so I can't just pick "the" ideal camera size or sprite scale because it can't be constant. I've tried using Canvas and its Pixel Perfect checkbox to no avail. I didn't really expect that to work though. What can I do to achieve the desired effect, then?
|
0 |
Can you use the RangeAttribute to limit the size of an array? I recently found out about the RangeAttribute and how you could use it to limit the values of your parameter when entering them in in the inspector window. However, I needed to use an array for randomly selecting Prefabs so they can spawn randomly at any given time. The problem is Unity lets me have an array size of zero, but I also want to limit the number of possible prefabs. I was wondering if there is a way to use RangedAttribute to limit the size of an array, and if not is there a different way to achieve this? I have extensive experience in Java and C but recently started in Unity, so I don't know if I'm asking the right questions, so any guidance right now would be greatly appreciated. Thanks. P.S. I would be able to attach the script to give an example if needed.
|
0 |
Simple Line Formation I'm working on the first formation for my game's troops. These should simply stand on land, facing the same direction. To achieve this, I tried to create offsets towards a pivot unit, that is approximately the unit in the center of the formation. The units are (temporary) elements of a squad list withing the Squad class. I divide the List by 2 and get the closest integer, that should be the pivot point of the formation. Now I generate offsets for all units on the left side (Unit 1 to pivot 1) and right (pivot 1 to last unit) based on the distance gaps. This is the code for the line formation. Sadly, the units are only forming a very stange line with no visually detectable system int count (int)(squadMembers.Count 2) pivot squadMembers count center pivot.transform.position switch (type) case FormationType.Line int space 5 for (int i 0 i lt squadMembers.Count i ) Unit tmp squadMembers i int dist 0 if (i gt count) dist (count 1) space center.x dist if (i lt count) dist (count 1) space center.x dist tmp.StartMove(center) break It also appears that this only works along the x axis, any idea how i can realize this with the walking facing direction ov the pivot? Is there any (obvious) error? How can I improve this script? PS Any idea, how I can transform this into a double line (2 Lines behind with half spacing)
|
0 |
Unity3D GameObject as a static function Newbie Unity3D C developer here. I've tried learning Unity3D during my May June college vacation and came across a problem Code 1 CameraObj returnVoid void Start () returnVoid GameObject.Find ("Main Camera").GetComponent lt CameraObj gt () returnVoid.ComponentType () Code 2 GameObject returnDirectLight void Start () returnDirectLight GameObject.Find ("Directional Light") Debug.Log (returnDirectLight.GetComponent lt DRLight gt ().directionString) CameraObj is my custom component. As far as I know, GetComponent is actually a public method. I understand the logic behind Code 2. What I fail to understand is Code 1. How does GetComponent become a static function here? Does it become abstract in my CameraObj class?
|
0 |
How to save Unity assests to another drive? My C volume has almost no space left. Therefore I want to transfer all my assets to the volume E . And save my new assets automatically on the E volume. I have searched very long in unity for save options of unity assets but nowhere found a setting option for this.
|
0 |
unable to see sprite in scene Getting error as floating point precision limitation I am trying to create game object by dragging image from project window to scene I am getting error as due to floating point precision limitation it is recommended to bring the world coordinates of game object within smaller range I am following ruby's adventure tutorial in unity learning
|
0 |
Handling complex selection mechanics in RTS style game When we look at complex RTSs where a simple left button mouse click can mean twenty or more different things, depending on the game and UI state, the code handling this interaction and assigning the right interaction action to the input can easily end up messy and tightly coupled to everything, creating a ball of mud architecture The Class That Does Everything related to interaction. How can I deal with this situation? Here's an example of the complex selection mechanics that I'm looking for Single left click to select a friendly unit. If friendly unit is in a group, the group is selected. If the group is already selected, select the unit. Single left click to select an enemy unit. If friendly unit group already selected, then issue attack order on unit. If friendly unit group already selected and enemy unit is in an enemy group, then issue attack order on enemy group. Same thing but if target is allied non controllable, then friendlies move towards target. Etc. How can I handle this complex selection system, taking into account complex states?
|
0 |
Instantiate unity sometimes lags the game some times it doesnt I have a script that instantiates a object lets say every half a second. THis object is of the type .fbx and has a file size of 53kb, lets call this object A. When i use this object my script instantiates the objects without any freezes or any other problems. Now i have an other object also of type .fbx and also with a filesize of 53kb lets call this object B. Now when i want to instatiate object my my game freezes a few frames upon instantiation. Why? Is there a way to instatiate objects more efficiantly? I already looked at using object pooling but this doesnt really works in my case. See here a screenshot for object A, and its components See here object B and its components Per request the code that does the instantiation of the objects public class ForLoopVisualization1 MonoBehaviour public DetectorAreaScript ElementDetector public GameObject TowerElement public Transform TowerElementsParent public bool WigglyTower false public float ElementSpacing, Wiggeliness private Collider BuildElementCollider private Transform BuildElementTransform private Vector3 TowerElementPos private int TowerElementCount, CreatedElements private bool StartBuildingTower false private float Delay 0.5f, TowerElementSize Use this for initialization void Start () ElementDetector.DetectedData OnObjectEnterDetector Destroy(TowerElement.GetComponent lt Rigidbody gt ()) TowerElementSize TowerElement.GetComponent lt Collider gt ().bounds.size.y TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) Update is called once per frame void Update () if(StartBuildingTower amp amp CreatedElements lt TowerElementCount) Delay Time.deltaTime if(Delay lt 0) CreatedElements var te Instantiate(TowerElement, TowerElementPos, Quaternion.identity) te.transform.SetParent(TowerElementsParent) if(WigglyTower) TowerElementPos new Vector3(Random.Range( Wiggeliness, Wiggeliness), TowerElementSize ElementSpacing, Random.Range( Wiggeliness, Wiggeliness)) else TowerElementPos new Vector3(0, TowerElementSize ElementSpacing, 0) Delay 0.4f else if(StartBuildingTower) StartBuildingTower false StartCoroutine(EjectVar()) add when bugs are fixed.. void OnObjectEnterDetector(System.Object sender, DetectedVariableData data) if(data.DetectedObjectType DetectedType.Variable) var vals ElementDetector.DetectedVariable.GetVariableValue() TowerElementCount vals.IntValue if(CreatedElements gt 0) foreach (Transform child in TowerElementsParent) Destroy(child.gameObject) CreatedElements 0 TowerElementPos TowerElementsParent.position new Vector3(0, TowerElementSize 1.5f ElementSpacing, 0) StartBuildingTower true IEnumerator EjectVar() yield return new WaitForSeconds(0.8f) ElementDetector.EjectDetectedElement(new Vector3( 1, 0, 1)) If something is unclear let me know so i can clarify the post!
|
0 |
Cardboard VR Mode rendering black in Unity I've searched around and seen this problem is quite common, but none of the fixes I've read have resolved the issue If VR Mode is enabled in the GvrViewerMain prefab, the scene will render as just a black screen. I've set the Graphics API to OpenGLES2, I've disabled Multithreaded Rendering, I've disabled direct render, yet this continues to be an issue. This happens both within unity itself and if it is built and run to my phone. Has anybody encountered this problem do you know of any further steps to take to resolve the issue?
|
0 |
Using an objects velocity to determine if it falling on a player will kill it I've been attempting to make a falling object kill a player, but i still want to make sure the player can touch and interact with the object to move it around without dying. The code i've made so far somewhat works as it wont kill the player when they move it will kill the player when it falls and hits them, but the problem is it only works if they have not moved yet from their spawn position (could also be true for when they have stood still for a second). Here is my code using System.Collections using System.Collections.Generic using UnityEngine public class BoxyKill MonoBehaviour public Rigidbody2D rgbd public CharacterController2D character private void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.tag "Player") Debug.Log("Hit player") if (rgbd.velocity.y lt 5f) character.Damage(10) Debug.Log("Hit player 2") Note the 'rgbd' is the boxs and this script is attatched to the object Thanks! UPDATE So as of DMGregorys suggestions i have updated the code and while it works i have encountered the same problem (however a lot more controlable this time) Here is my current code public Rigidbody2D body private float minimumDamageThreshold 10 private float collisionDamageScale .0001f void OnCollisionEnter2D(Collision2D collision) Vector2 normal collision.GetContact(0).normal Vector2 impulse ComputeTotalImpulse(collision) Vector2 myIncidentVelocity body.velocity (impulse body.mass) Vector2 otherIncidentVelocity Vector2.zero var otherBody collision.rigidbody if (otherBody ! null) otherIncidentVelocity otherBody.velocity if (!otherBody.isKinematic) otherIncidentVelocity impulse otherBody.mass Compute how fast each one was moving along the collision normal, Or zero if we were moving against the normal. float myApproach Mathf.Max(0f, Vector3.Dot(myIncidentVelocity, normal)) float otherApproach Mathf.Max(0f, Vector3.Dot(otherIncidentVelocity, normal)) float damage otherApproach myApproach Debug.Log(damage) character.Damage(damage) static Vector2 ComputeTotalImpulse(Collision2D collision) Vector2 impulse Vector2.zero int contactCount collision.contactCount for (int i 0 i lt contactCount i ) var contact collision.GetContact(0) impulse contact.normal contact.normalImpulse impulse.x contact.tangentImpulse contact.normal.y impulse.y contact.tangentImpulse contact.normal.x return impulse It now works and will kill the player, and i have it printing out the damage in the debug for the character script damage function. The only problem is, it will constantly damage the player if it touches the box at all, and the player needs to be able to move the box around so this will slowly kill it. This could be a problem with the variable amounts that i have configured due to a lack of understanding (and a lot of mindless fideling to be honest).
|
0 |
How can I reflect a point about a line in Unity? I am drawing a line using the line renderer in the following way public class MyLineRenderer MonoBehaviour LineRenderer lineRenderer public Vector3 p0, p1 Use this for initialization void Start () lineRenderer gameObject.GetComponent lt LineRenderer gt () lineRenderer.positionCount 2 lineRenderer.SetPosition(0, p0) lineRenderer.SetPosition(1, p1) From the image below, the line P0P1 is known and so is point A. How can a point B, which is the reflection of A about the line P0P1 be found?
|
0 |
In Unity, why does my IndexOutOfRange exception disappear when trying to debug it? I don't get errors when playing from Unity "Game" tab. But when I build an executable (development or not) it stucks. I get "IndexOutOfRange" exception. Which also magically disappears (yes) when I add some debug lines This does not work for (int i x1 i lt x2 i ) for (int j y1 j lt y2 j ) int a, b a 7 i Out of range b 7 j Out of range submap a, b world.WalkableMap (int)CurrentWalkableTile.x i, (int)CurrentWalkableTile.y j This works for (int i x1 i lt x2 i ) for (int j y1 j lt y2 j ) int a, b a 7 i b 7 j if (a lt 0 a gt 15) now with this never gets out of range Debug.Log("A out of range " a) if (b lt 0 b gt 15) now with this never gets out of range Debug.Log("B out of range " b) submap a, b world.WalkableMap (int)CurrentWalkableTile.x i, (int)CurrentWalkableTile.y j I can't find any sense. The exception literally hides from me Additional info maybe is useful x1 (CurrentWalkableTile.x 7) gt 0 ? 7 (int)CurrentWalkableTile.x x2 (CurrentWalkableTile.x 7) lt world.wmap x size ? 7 (world.wmap x size (int)CurrentWalkableTile.x 1) y1 (CurrentWalkableTile.y 7) gt 0 ? 7 (int)CurrentWalkableTile.y y2 (CurrentWalkableTile.y 7) lt world.wmap y size ? 7 (world.wmap y size (int)CurrentWalkableTile.y 1) I'd like to post more information, but I can't even debug to find the problem.
|
0 |
Delay Pause game while displaying countdown 3,2,1 go I have already a running script of countdown and it works fine , the problem is that I want to pause or delay the game while the countdown is displaying, the moment countdown finished the player is already dead. Here is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class jb MonoBehaviour private string countdown "" private bool showCountdown false public AudioSource noise1 public AudioSource noise2 public Sprite sprite2 public Vector2 jump new Vector2 (0,300) private SpriteRenderer spriteRenderer void Start () GetComponent lt Rigidbody2D gt ().velocity Vector2.right speed StartCoroutine(getReady()) spriteRenderer GetComponent lt SpriteRenderer gt () noise1.GetComponent lt AudioSource gt ().Play() Update is called once per frame void Update () if(Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) Vector2 touchPosition Input.GetTouch(0).position GetComponent lt Rigidbody2D gt ().AddForce(jump) noise1.GetComponent lt AudioSource gt ().Play() Vector2 screen position Camera.main.WorldToScreenPoint (transform.position) if(screen position.y gt Screen.height screen position.y lt 0) noise1.GetComponent lt AudioSource gt ().Stop() noise2.GetComponent lt AudioSource gt ().Play() StartCoroutine(Die()) void OnCollisionEnter2D(Collision2D det) noise1.GetComponent lt AudioSource gt ().Stop() noise2.GetComponent lt AudioSource gt ().Play() StartCoroutine(Die()) IEnumerator Die() PlayerPrefs.SetString( "previousLevel", SceneManager.GetActiveScene().name ) spriteRenderer.sprite sprite2 yield return new WaitForSeconds (2) SceneManager.LoadScene("score") IEnumerator getReady() showCountdown true countdown "3" yield return new WaitForSeconds (1) countdown "2" yield return new WaitForSeconds (1) countdown "1" yield return new WaitForSeconds (1) countdown "GO" yield return new WaitForSeconds (1) showCountdown true countdown "" void OnGUI () if (showCountdown) GUI.color Color.red GUI.Box ( new Rect (Screen.width 2 100, 50, 200, 175), "GET READY") display countdown GUI.color Color.white GUI.Box (new Rect (Screen.width 2 90, 75, 180, 140), countdown) what can I do to pause the game? I tried invoke (by creating another function and copying everything over there) in update call but it didn't work.
|
0 |
Unity UI Raw Image with Texture becomes Smaller after Build I am a beginner in the game development world, I have just one quick problem with the UI, as you can see during the Unity Player, the UI (Raw Image w Texture) is normal in size but when I build my game to APK or EXE and run it, the UI is small. Why is this happening and how to fix it?
|
0 |
pick up material from another object is it possible to obtain a material from another object? I'm trying everything and nothing, the only thing I could get was just the color of another object public MeshRenderer takematerial public GameObject Objects for (int i 0 i lt Objects.Length i ) Objects i .GetComponent lt Renderer gt ().material takematerial.material
|
0 |
addressables unity unknown async error public AssetLabelReference imgs List lt IResourceLocation gt myImgs new List lt IResourceLocation gt () SerializeField List lt Texture2D gt loadedImages new List lt Texture2D gt () private void Start() Addressables.LoadResourceLocationsAsync(imgs.labelString).Completed imgReady void imgReady(AsyncOperationHandle lt IList lt IResourceLocation gt gt op) myImgs new List lt IResourceLocation gt (op.Result) insta() void insta() Addressables.LoadAssetsAsync lt Texture2D gt (myImgs, cb) void cb(Texture2D s) loadedImages.Add(s) I get the locations of the images but not the asset themselves I get an error of Exception encountered in operation Resource(Man.png) Unknown error in AsyncOperation UnityEngine.ResourceManagement.Util.DelayedActionManager LateUpdate() (at
|
0 |
since unity upgrade, OnSceneLoaded not getting called on scene start I upgraded my unity project to 2018.3.11f. Since that upgrade, the OnSceneLoaded event is not getting called, even though I am registering the event handler. Here's the class public class SceneSwitcher MonoBehaviour void OnSceneLoaded(Scene scene, LoadSceneMode mode) print("scene loaded " scene.name) void Start() print("SceneSwitcher.Start() called") print("adding event handler to SceneManager") SceneManager.sceneLoaded OnSceneLoaded here's the console output SceneSwitcher.Start() called UnityEngine.MonoBehaviour print(Object) SceneSwitcher Start() (at Assets Scripts SceneSwitcher.cs 45) adding event handler to SceneManager UnityEngine.MonoBehaviour print(Object) SceneSwitcher Start() (at Assets Scripts SceneSwitcher.cs 46) scene loaded 3 is never in the console output. I see others have had this problem, with no answers. This code worked before the upgrade. Now I am stuck. Not sure what I can do. Any help is appreciated. Thnx
|
0 |
How to teleport a game object to an empty game object? I am trying to make a respawn system where if the player touches a plane, (the name of the object is tutlvl1 flrdead) they get teleported to an empty object at player spawn named quot RESPAWN quot . But, several tutorials and unity answers threads lead me to nowhere since they were written from back in 2013 or somewhere around there. Code using System.Collections using System.Collections.Generic using UnityEngine public class deathfloor MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() public gameObject myObject You can name it whatever you want. myObject.transform.position new Vector3(3.076, 1.74, 3.651) How can I fix this to do what I need for my game?
|
0 |
Unity Moving player using Rigidbody with UI Buttons? i have been using transform.positionsince the start but now i want to switch to rigidbody instead since i am facing some collision problems. i can use the keyboard to move the player using this code input new Vector3 (Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")) if (GetComponent lt Rigidbody gt ().velocity.magnitude lt maxmovespeed) GetComponent lt Rigidbody gt ().AddForce (input movespeed) but since i am building for mobile and have added UI buttons for right left on screen, i wish to use those for moving my player. how can i use those buttons to move in that specific direction like left for left only and right for right?
|
0 |
Convert linear velocity to angular velocity for a ball sphere (Rolling Ball Maths) I have a ball moving on a flat plane. I cannot use RigidBody physics, so my object in Kinematic and I am manually handling speed acceleration. The linear movement of the ball is fine, however as the ball does not rotate, it looks odd. Given a speed Vector3, where I am moving on the X amp Z, I need to figure out how to make the ball "roll". I think I a running into Euler Gimbal lock issues by trying this transform.Rotate( 180.0f speed.z (Mathf.PI radius) dt, 0, 180.0f speed.x (Mathf.PI radius) dt ) This formula is loosely based on the angular velocity formula and converting to degree's per second, with dt (deltaTime). My gut instinct says that the solution may lie in Quaternions somewehere...?!
|
0 |
Unity 5.6.0f3 Inspector Tooltips are off in macOS, is me or everyone the same? Running latest version (5.6.0f3) in macOS, my tooltips are always misalign to the left of my screen, is me or anyone else also experience the same? And, it is still misalign even after I reset the layout setting to factory default. Here are the screenshots http imgur.com a dR0Pv Update Filed a bug report.
|
0 |
Unity Bullet spawns in wrong position in client I am making a multiplayer game with prefab shooting, but unfortunately the prefab sometimes spawns in the wrong position when I shoot from a client. The bullet tends to spawn in a location where the player was a few miliseconds ago, making that the bullet sometimes spawns inside of the player which killing the player in the process. For shooting, I currently have this code setup to instantiate the bullet void Update() if (Input.GetMouseButtonDown(0)) float angle GetComponentInChildren lt Weapon gt ().angle CmdShootBullet(angle) rigidbody.AddForce(Quaternion.AngleAxis(angle 180, Vector3.forward) Vector3.right (bulletPrefab.GetComponent lt Bullet gt ().force 7.5f)) Command void CmdShootBullet (float angle) GameObject bullet Instantiate(bulletPrefab, firePoint.position, Quaternion.identity) Bullet bulletScript bullet.GetComponent lt Bullet gt () bulletScript.shotBy gameObject bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) Vector3.right bulletScript.force) NetworkServer.Spawn(bullet) And this is the setup for the location of the player and the gun. The top one is the player, the bottom is the gun. My guess is that it has to do with lag, that the player position does not update soon enough, so how would I make it that the bullet spawns in the position of the player in the client rather than the position of the player in the host?
|
0 |
Buttons only trigger right left movement once, not continually I have a Unity mobile project where I am trying to use right left movement using two UI buttons situated accordingly. The issue is that it only moves the player to the right to the left one time, not continually when the player is holding the button down. I'd like the player to be able to hold down a certain button and have the character move constantly in that direction until the button is released. I've tried making the void into a Coroutine, but nothing working works. Here is my code. (rightCallable and leftCallable are attached to the buttons). using System.Collections using System.Collections.Generic using UnityEngine public class playerController MonoBehaviour public GameObject player public float speed 1000f public GameObject left this is so the player may also use the A and D keys if they want, and it works fine. public void Update() var movement Input.GetAxis( quot Horizontal quot ) transform.position new Vector3(movement, 0, 0) Time.deltaTime speed Below is what isn't working public void rightCallable () StartCoroutine( quot moveRight quot ) public void leftCallable () StartCoroutine( quot moveLeft quot ) IEnumerator moveRight() var movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed yield return null IEnumerator moveLeft () var movement 1f transform.position new Vector3(movement, 0, 0) Time.deltaTime speed yield return null
|
0 |
object reference not set to an instance of an object hello i have a error "object reference not set to an instance of an object" when my ball collide with the spikes.its supose to remove one heart but it doesnt. health code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Health MonoBehaviour public int health public int numOfHearts public Image hearts public Sprite fullHeart Use this for initialization void Start () Update is called once per frame void Update () if (health gt numOfHearts) health numOfHearts for (int i 0 i lt hearts.Length i ) if (i lt health) hearts i .sprite fullHeart if (i lt numOfHearts) hearts i .enabled true else hearts i .enabled false public void Damage(int dmg) numOfHearts dmg spikes code using System.Collections using System.Collections.Generic using UnityEngine public class Spikes MonoBehaviour private Health Player Use this for initialization void Start () Player GameObject.FindGameObjectWithTag("Player").GetComponent lt Health gt () Update is called once per frame void Update () void OnTriggerEnter2D(Collider2D col) if (col.CompareTag("Player")) Player.Damage(1) here i have the error.
|
0 |
Build a Unity asset bundle on linux? I'm trying to generate an asset bundle on a remote linux machine and stream the bundle to a running Unity instance. Is it possible to download the same libraries Unity uses and compile on Linux?
|
0 |
How to apply outer glow to a UI game object? Shader? Particle? What's the best or easiest approach to apply an outer glow effect to a UI game object let's say, a popup dialog, so it's a rectangular shape in Unity 2018.3? Is this something that should be done with a shader, or is it a particle effect? Ideally I should be able to specify and perhaps even dynamically adjust the color and size of the glow. Edit image below shows a blue rectangle, which has this subtle, grey glow around it. I'm hoping to generate this glow effect somehow in Unity.
|
0 |
Disable free look camera movement when touch detected on mobile joystick I'm using free joystick pack form asset store and in scene have two cameras (first person and third person). Switching cameras with toggle. Game starts with first person camera. Moving with fixed joystick and rotating camera with swiping on right side of screen. Everything is ok for this step. For third person camera I'm using cinemachine free look camera. Cinemachine camera is reacting to joystick touch inputs. I need to disable camera movement when interacting with joystick. Tested on Android device Cinemachine settings Third Person movement script void Update() if (Application.platform RuntimePlatform.Android Application.platform RuntimePlatform.IPhonePlayer) x joystick.Horizontal z joystick.Vertical else x Input.GetAxis( quot Horizontal quot ) z Input.GetAxis( quot Vertical quot ) Vector3 direction new Vector3(x, 0, z).normalized if (direction.magnitude gt 0.1f) float targetAngle Mathf.Atan2(direction.x, direction.z) Mathf.Rad2Deg camTps.transform.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 characterController.Move(moveDirection.normalized speedTps Time.deltaTime) Any ideas and suggestions is appreciated
|
0 |
How to use GameManager to get GameOver() from another script? I'm trying to make a gameover text show when the player is leaving the plane area. In GameManager.cs I've written public void GameOver() gameOverText.gameObject.SetActive(true) And in PlayerController.cs I've used the following code private GameManager gameManager and void Update() float horizontalInput Input.GetAxis("Horizontal") float verticalInput Input.GetAxis("Vertical") playerRb.AddForce(Vector3.right speed horizontalInput) playerRb.AddForce(Vector3.forward speed verticalInput) if (transform.position.y lt 4) gameManager.GameOver() But this doesn't really work, and the console is giving me this message Assets Scripts PlayerController.cs(8,25) warning CS0649 Field 'PlayerController.gameManager' is never assigned to, and will always have its default value null I've already used the OnTriggerEnter (for powerups) and OnCollisionEnter (for enemies). How can I get the GameOver text to show when the player leaves the "Plane"?
|
0 |
Unity 2D Cinemachine weird behavior for non rectangular confiner I have been trying to emulate a sort of Megaman X4 way of following the player around platforming levels, where the camera is confined to certain boundaries of such levels. However, all the tutorials and guides out there only show rectangular or square shaped confiners for the virtual cameras, and not odd shapes like an L shaped confiner, when using a weirdly shaped confiner the camera just tends to snap from one position to another and the game ends up feeling bad when that happens. I have tried solving this problem by using dolly tracks, which work nicely... But I end up having tons of virtual cameras to change to on sections that are weirdly shaped since the camera ends up also suddenly snapping on to weird positions on sharp turns and it also tends to get way off track, even when the settings of the virtual camera are configured to have very little damping and if there's no damping the camera just stutters all the time. Is there a way to have this kind of behavior to confine a virtual camera to oddly shaped level boundaries?
|
0 |
How to rotate and move an object in precise time frame My task is to rotate and move an object into a new position and rotation in a given time. Say I have to move a cube from (0,0,0) (0,0,0) to (1,1,1) (0,90,0) in 5 seconds. Could anyone explain to me please how to achieve that? My experiment is private IEnumerator DoMove( float time, Vector3 targetPosition ) foreach(WayPoints wp in tposes) float counter 0 float duration wp.timeStamp while (counter lt duration) counter Time.deltaTime Vector3 curpos cube.transform.position Quaternion crot cube.transform.rotation float time Vector3.Distance(curpos, wp.position.position) (duration counter) Time.deltaTime cube.transform.position Vector3.MoveTowards(curpos, wp.position.position, time) cube.transform.rotation Quaternion.Lerp(crot, wp.position.rotation, time) yield return null Debug.Log( quot Reached position quot wp.position.position quot in time quot Time.time) The cube gets to its position in time, but rotation is late. The end position of the cube should be (2,2,2) (0,120,0), but it stops moving at (2,2,2) (0, 110,0). There are two positions I want the cube to be in (1,1,1) (0,90,0) in 5 seconds (2,2,2) (0,120,0) in next 4 seconds
|
0 |
How do you generate seamless Perlin noise? I've done a research and tried implementing for months, but I've gotten nowhere trying to make seamless tileable Perlin noise. Here is my current Perlin noise file without seamless implementation. In my program, I am calling FractionalBrownianMotion to generate. Each of the research articles have given me issues. In FractionalBrownianMotion I change the call from Perlin to PerlinSeamless. Research Articles How to make one axis tileable simplex noise? Produces broken noise using x2, y2 as period xsize, ysize as map size. Also tried vice versa. Added code public float PerlinSeamless(float x, float y) int width gradientArray.GetLength(0) int length gradientArray.GetLength(1) map size 250 float x1 0, x2 50 float y1 0, y2 50 float dx x2 x1 float dy y2 y1 Sample noise at smaller intervals float s x width float t y length Calculate our 3D coordinates float nx x1 Mathf.Cos(s 2 Mathf.PI) dx (2 Mathf.PI) float ny y1 Mathf.Sin(t 2 Mathf.PI) dy (2 Mathf.PI) float nz t return Perlin3D(nx, ny, nz) public float Perlin3D(float x, float y, float z) y 1 z 2 float xy perlin3DFixed(x, y) float xz perlin3DFixed(x, z) float yz perlin3DFixed(y, z) float yx perlin3DFixed(y, x) float zx perlin3DFixed(z, x) float zy perlin3DFixed(z, y) return xy xz yz yx zx zy private float perlin3DFixed(float a, float b) return Mathf.Sin(Mathf.PI Perlin(a, b)) How do you generate tileable Perlin noise? hashed perm perm int(gridX) per int(gridY) per goes OOB. 3D Perlin Noise Technique does not replicate 2D noise when z value always 0, but using this method for 3D Perlin noise assuming that's the way it's supposed to be I have also tried various implementations of non answer accepted comments in these articles to see only broken noise.
|
0 |
Jittery collisions in Unity 2D I tried to implement a simple movement to my object. My object moves perfectly fine but I'm having issues with its collision. When I keep on moving object towards the obstacle ground, collision are jittery. Here the code for what I've written. using System.Collections using System.Collections.Generic using UnityEngine public class TempScript MonoBehaviour SerializeField float walk speed 5f SerializeField float jump speed 10f SerializeField float max up 7f SerializeField float max low 1.5f void Update() PlayerMovement() void PlayerMovement() if (Input.GetKey(KeyCode.W) amp amp transform.position.y lt max up) transform.position transform.position Vector3.up jump speed Time.deltaTime if (Input.GetKey(KeyCode.S) amp amp transform.position.y gt max low) transform.position transform.position Vector3.down jump speed Time.deltaTime if (Input.GetKey(KeyCode.D)) transform.position transform.position Vector3.right walk speed Time.deltaTime if (Input.GetKey(KeyCode.A)) transform.position transform.position Vector3.left walk speed Time.deltaTime The cube goes below the ground and bounces right back up. making it look like its jittering. what i want is movement should stop when its colliding with object. just like it happens with addForce method. for now you can ignore max up and max down variable, it was just to make sure its in the camera.
|
0 |
Unity SpriteAtlas memory consumption I'm in the process of optimizing my application memory consumption. To do so, I'm using Unity profiler while connecting to an Android device, which runs a development build of the application. The application is using two types of sprite containers Sprite sheets created by the Texture packer. Sprite Atlases created by unity. Using the profiler, it is observed that while the sprite sheets (created by the Texture packer) take the expected amount of RAM, the sprite atlases created by unity consume DOUBLE the expected amount of RAM. For example, the sprite atlas UIATLAS, whose size is 4096x4096 is supposed to consume 16MB of RAM But looking at the profiler, after running "Take Sample", you see the value 32MB My sprite atlas settings are Any help is welcome here. One more comment (please review) UIAtlas belongs to an asset bundle called "atlas ui". It is defined on several directories containing its sprites, all of which belong to the same asset bundle, atlas ui. Is that the correct way to define it? Thanks in advance!
|
0 |
GeForce FPS Counter is not displaying and G SYNC is not working on games developed using Unity I have developed a small game for learning purpose and here is src of that, when I play the game GeForce FPS Counter is not displaying. I thought there might be some kind of bug in my src. So, I installed two popular games developed using Unity. "Life is Strange Before the Storm" FPS not displaying. "INSIDE" FPS displaying. Can anyone tell me what is happening. And also I noticed that when playing "Life is Strange Before the Storm" my CPU and GPU temperature goes hotter than playing "Rise of the Tomb Raider". Note I have played all the game in full screen mode and all settings to highest. UPDATE Firewatch and INSIDE both shows FPS Counter. but, when Enable G SYNC for full screen mode is selected, G SYNC is not working in all the games developed using Unity even when launched in full screen mode. But when I enable Enable G SYNC for windowed and full screen mode then the G SYNC is working. But when it comes to Life is Strange Before the Storm is not showing FPS Counter but shows G SYNC indicator on the screen. Is Unity games not actually runs in Full Screen mode?
|
0 |
Can I run old projects after updating Unity? Today I decided to upgrade unity from 5.0.0 to 5.5.0. But before updating it, I wanted to know Can I run build my projects made in Unity 5.0.0 in Unity 5.5.0?
|
0 |
Switching character and keeping animations in Unity default third person controller This is probably a ridiculous question, but I am doing a school project in Unity and am trying to create a basic game. For movement I want to use third person controller and since this is very basic I wanted to keep the default 3d model of character as well (Ethan). But since it is so colorless I had a friend of mine to color it up and then export it back to unity. The problem is that it's a different model now and animations don't work anymore so I want to know how to correctly switch them to keep default animations? The models are the same otherwise so animations should be possible to apply. Since nothing I tried so far didn't help I really hope someone can give me some instructions.. ) Thanks
|
0 |
How can I ensure a radius variable doesn't get reduced below 0? For some reason when I'm using the mouse to change the radius in the Update, the minimum radius is 1 even if I set the range in the top of the script to be 0,50 and even if I check that the xradius is be 0 or higher it's still getting to 1. using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using System RequireComponent(typeof(LineRenderer)) public class DrawCircle MonoBehaviour Range(0, 50) public int segments 50 public bool circle true Range(0, 50) public float xradius 15 Range(0, 50) public float yradius 15 LineRenderer line public float drawSpeed 0.3f void Start() line gameObject.GetComponent lt LineRenderer gt () line.positionCount (segments 1) line.useWorldSpace false private void Update() if (xradius gt 0) if (Input.GetAxis("Mouse X") lt 0) xradius xradius 1 CreatePoints() if (Input.GetAxis("Mouse X") gt 0) xradius xradius 1 CreatePoints() private void CreatePoints() if (circle true) yradius xradius float x float z float change 2 (float)Math.PI segments float angle change for (int i 0 i lt (segments 1) i ) x Mathf.Sin(angle) xradius z Mathf.Cos(angle) yradius line.SetPosition((int)i, new Vector3(x, 0.5f, z)) angle change In the Update I did if (xradius gt 0) But yet when using the mouse for the minimum radius it set both xradius and yradius in the sliders to 1 not sure how can it be 1 if I set the range in both xradius and yradius to be 0,50 You can see in the screenshot in the Inspector in the right both Xradius and Yradius are 1
|
0 |
2D Lock x Axis on character I am creating an endless runner with a flying character. I want to lock any movement in the x axis so that the character object can only move up and down but still move forward through the scene. I have looked into freezing axes and joints, but this stops the forward movement. Is it possible to edit the below to lock the x axis for character movement only, or is there a setting where i can apply this? using UnityEngine using System.Collections public class moveupdown MonoBehaviour public Vector2 velocity public float uservelocity public Rigidbody2D rb2D void Start() rb2D GetComponent lt Rigidbody2D gt () void FixedUpdate() if (Input.touchCount gt 0 amp amp Input.GetTouch (0).phase TouchPhase.Moved) Vector2 touchDeltaPosition Input.GetTouch (0).deltaPosition rb2D.MovePosition (rb2D.position touchDeltaPosition Time.fixedDeltaTime uservelocity)
|
0 |
Render Occluded pixels to gray color In 3d space, objects can be occluded by another objects. By depth testing, the occluded faces are skipped rendering. Only the nearest(smallest) depth value pixels are drawn. But, sometime we need to render the occluded object or pixels for game play. To differentiate the occluded object's pixels from foreground pixels, some game use gray color to render the pixels. This is the sample images for the case. I guess this can be achieved by some sort of shader. How can I make this effects in Unity 3D Engine? Any hints or idea plz.
|
0 |
Oscillate an object's scale I am able to scale an object using a scaling function I wrote. Internally it builds matrices that are multiplied by each of the vertices to transform them. The parameters I give the scaling function tell it how much to scale the object by as a factor of its current scale. I want my object's scale to smoothly oscillate between two values, so I have used Sin waves to build my scaling factor, which is 1 amplitude (Mathf.Sin(2 Mathf.PI frequency Time.time) Mathf.Sin(2 Mathf.PI frequency (Time.time Time.deltaTime))) The result looks very close to what I want, but with each oscillation, the object gets slightly smaller than before. The problem is that my function is written so that it scales the vertices as a factor of its 'current' scale, which is always changing.
|
0 |
Scene for Computer Screen We are developing a scene that will involve heavily interacting with a "touch screen monitor" in the scene.. Because the workflow of the touch screen will need to be dynamic we are creating a REST API that Unity will fetch JSON data and use that to build out the various parts of the UI. For instance, we get a JSON file that has a list of users and attributes and build out UI elements with that data. The question is should I build out the display and underlying logic as a 2D scene that I add in to our 3D room or just build it all in the 3D scene. I want to abstract away as much of the logic as I can for the interactive screen I want to make sure we can drop this screen in a different Scene down the road without too much reverse engineering. Sorry if this is a straightforward question, my background is software dev, not game design.
|
0 |
How can I deactivate and activate a button? I have a code that keeps a gameObject between scenes, the theme is that this gameObjecte has as a child a button, which I can change the linerenderer color, besides changing the image of the button according to the selected color and thus keep the data between scenes. then when I change to the next scene I deactivate the button with the meteodo "dehabilitar()" and in the others it is not necessary, then when I change to the next scene I deactivate the button and it is not shown, but when I go back to the next scene and call the function " habilitar() "the button is not displayed. If someone can help me in what I have bad in the code or what I lack? PS I did different methods to activate and deactivate the button but the same thing always happens and I leave it like that for a while. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI namesp ace DigitalRubyShared public class CambioColor MonoBehaviour public Button mybutton public LineRenderer p1 public LineRenderer p2 public Sprite colorRojo Color Rojo new Color(1, 0, 0, 1) public Sprite colorAzul Color Azul new Color(0, 0, 1, 1) public static int counter 0 public static bool estado false public static CambioColor estadoCambioColor void Awake() if (estadoCambioColor null) estadoCambioColor this DontDestroyOnLoad(gameObject) else if (estadoCambioColor ! this) Destroy(gameObject) void Start() mybutton GetComponent lt Button gt () p1 GetComponent lt LineRenderer gt () p2 GetComponent lt LineRenderer gt () counter 2 public void changeColor() counter if (counter 1) mybutton.image.overrideSprite colorAzul mybutton.image.sprite colorAzul p1.startColor Azul p1.endColor Azul p2.startColor Azul p2.endColor Azul if (counter 2) mybutton.image.overrideSprite colorRojo mybutton.image.sprite colorRojo p1.startColor Rojo p1.endColor Rojo p2.startColor Rojo p2.endColor Rojo counter 0 public void dehabilitar() if (estado false) mybutton.enabled estado mybutton.gameObject.SetActive(estado) estado true public void habilitar() if(estado true) mybutton.enabled estado mybutton.gameObject.SetActive(estado) estado false Update is called once per frame void Update()
|
0 |
How to implement ECS architecture in C ? As C is a strongly typed language, I'm having great difficulties associating all my data types together so that I can have a clean, if not performant, game loop. Example 1 Keeping Components Together Keeping components together means I need an interface or base class to store them in an array, which would require keeping track of each type separately so that it can be converted back to the derived type before being consumed. The constant type conversion seems like a bad idea in an ECS? To compound the problem, I would prefer to use structs instead of classes for my components, which when cast to an interface will cause boxing. In some simple stop watch tests I've run it seems the casting boxing is 16x slower than just looping over the raw type. (Pseudo code below) IComponent sprite new SpriteComponentStruct() boxing for(int i 0 i lt iComponents.Length i ) var type GetComponentTypeByIndex(i) var system GetSystemWithType(type) SpriteComponent sprite Convert.ChangeType(...) system.Execute(sprite) Example 2 Keeping Components Separate To keep components separately in their own classes managers systems I would likely need a generic class to cut down on the code duplication. The problem I run into here is that looping over each class will require a base class or interface, which at the very least would force me to cast the component types again. (Pseudo code below) ComponentManager lt T gt () where T struct T components can't use with non generic interface to put manager into a list public void AddComponent(T component) ... won't compile type "T" will not cast to type "T" public void AddComponent lt T gt (T Component) ... requires casting and or boxing, which defeats the purpose of keeping components separate public void AddComponent(object component) ... It seems every which way I try to implement a ECS in C ends with hacky non performant code, that's assuming I can get it to compile in the first place. From studying other ECS systems around the net, it seems some side step these issues by using void int pointers or storing component bytes directly in memory (like I believe the new ECS in Unity 2018 does). Either way those are unsafe operations in what's supposed to be a managed memory language. So is C the wrong tool for the job? Am I approaching this incorrectly? I'd love to hear some opinions as this just seem impossible...
|
0 |
2D Camera sizing and movement Apologies if this is a basic question, or been asked a 1,000 times in the past... I'm new to Unity, and having problems understanding some of the basics to do with 2D cameras (orthographic), and while I've read a lot nothing has made me have that 'ah ah!' moment yet. What I'm trying to create is the following (camera position depicted by the box with the pink dashed line) where the yellow filled boxes are made up of a whole bunch of sprites. Overtime, the camera need to move left to right, and then bottom to top... What my issue seems to be is understanding how I can get the camera to display all of the sprites in other words, resize the camera view to fit the background sprite's height, and know when to stop the camera in order to start moving it up. What I'd like to understand is how and why to solve this problem it's the only way I'll learn! Thanks Kieron
|
0 |
How to get Flare elements? Is it possible to get the elements or the textures of a Flare and to change them at runtime? If so, then how do I get them? Pseudocode Flare flare GetComponent lt Flare gt () foreach (Element e in flare) e.Size 10 e.Color Color.green Thanks in advance )
|
0 |
Access buttons individually made by a for loop (old Unity GUI, Unity Editor script) I've got a problem and I am struggling with this for a couple of days now. I am making an Editor script and I want to access buttons individually when created by a for loop. There is a public class ButtonNode which stores some variables of the button like name and size. public class ButtonNode public bool button public string name "O" public float sizeW 25f public void AlterButton() name "P" Then there is my Editor script in which I create the buttons. This is where I get stuck, how do I access these buttons individually? For example, I want to change the name of the button when that button is clicked. How do I do that? Because they are booleans (I don't really know why, this is the legacy GUI) I can't access the transform.name components etc). public static ButtonNode bn new ButtonNode 10 void OnGUI() GUILayout.BeginHorizontal() for (int i 0 i lt bn.length i ) bn i new ButtonNode() if (bn i .button GUILayout.Button(bn i .name i, GUILayout.Width(bn i .sizeW))) bn i .AlterButton() GUILayout.EndHorizontal()
|
0 |
Array with multiple linked objects in Unity This might be too primitive, but for my use case, I need to maintain an array in which two attributes are linked to each other... For example If I want to do Score gathering... Then I need an array which has scores and corresponding player names as each element. So, when I do Array.Sort(PlayerScorearray) I even need the playername to be sorted in the order so that if I want to know the player with lowest score, I just go for the first element and then go to the corresponding player name.. Is it possible to do it in a simpler way? My mind can't think of a simple way to do this. Edit I am using C for scripts
|
0 |
Can I use flat shading on a generated mesh? I tried to generate a mesh from code in Unity. The problem is, that the edges are automatically smoothed. When I import a model into Unity, I can set the smoothing angle of the edges, but is something like this possible with a generated mesh? I would like to have no smoothing at all.
|
0 |
Jump a gameobject when a key is pressed I am working on a platform game,When I press the space bar the object should jump and when I release the space bar it should come down. The code I have used for jump is void Update () transform.Translate(Vector3.right Time.deltaTime) if(Input.GetKey(KeyCode.Space)) rigidbody2D.AddForce(Vector3.up 3) if(Input.GetKeyUp(KeyCode.Space)) rigidbody2D.AddForce(Vector3.down) But when I release the space bar the object is not coming down
|
0 |
Shadow Glitch on Mesh Stitches I use LWRP, one Directional Light and Hard Shadows with 1024 resolution. When I imported this super simple mesh from blender this happened What is this weird line on the stitch of the mesh and how do I fix it? I tried using Soft Shadows with higher quality but it did not help.
|
0 |
How do I use guilayout toggle event to check if true or false? OnGUI() for (int i 0 i lt scenes i ) GUILayout.Toggle(false, SceneManager.GetSceneAt(i).name) if (GUILayout.Toggle(true, "New Scene")) Debug.Log("True now !") First in the loop I'm adding some toggles. Then I want to do that if specific toggle is checked(true) do something and if unchecked(false) do something else. But the way I did it it's just changing the toggle to true automatic.
|
0 |
Get mouse touch position for NGUI event Since I am using NGUI, to capture mouse events I use their methods such as void OnPress (bool isDown) How can I check the mouse touch position that corresponds to this particular OnPress event?
|
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 to set up bloom in Unity Last time I used image effects in Unity it was back when 3.0 was released and for bloom you used the object's alpha to indicate whether it should glow or not. Now in 4.2 I couldn't grasp how to apply the image effect properly. It seemed to put the whole scene to glow and alpha did not affect it. There was no help from the Unity docs which are pretty much just spec sheets for the effects and no proper tutorials around. This leads to couple of questions How do you create something like the screenshots in the Bloom page in the docs? Only the car windows and metal parts glow, but no glow on the concrete. How do you make a light source like the second image on the above link? I tried different shaders and lights on a gameobject but none of them produced anything like that. What does the HDR checkbox in the camera actually do?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.