_id
int64
0
49
text
stringlengths
71
4.19k
0
Manually creating an instance of object derived from MonoBehaviour I'm currently "newing" an instance of a class I have that derives from MonoBehaviour and store it in a list. The value of this instance is "null" however, even though it has all the fields of my derived class in it so it passes as null in null checks. After more reading it seems it's a bad idea to manually new up an instance of an object that derives from MonoBehaviour. The class is an Actor class. I have a situation where enemy actors are 3D models in my scene and so I want them to derive from MonoBehaviour, but the player actors don't have world representations really. I just have a picture of them in the corner. Similar to Legend of Grimrock. I wanted the 1 Actor class since the data they need is all the same and I wanted to avoid having 2 classes for no seemingly reason other than not newing up a MonoBehaviour derived class. What are my options with this requirement when my player actors don't need MonoBehaviour but my enemy actors do but they all need to have the same properties?
0
unity JsonUtility.ToJson returns empty string I am trying to use Unity's built in json serialization. It produces empty string. I do not understand why. (I was trying to use NewtonSoft Json.Net but that wasn't working either even though I was following instructions). Here's the serialization code public class Player MonoBehaviour void Start () Mission a new Mission() Id 1, Name "Speak to the Farmer", State MissionState.OnGoing, Parent 1, Type MissionType.Main string json JsonUtility.ToJson(a) System.IO.File.WriteAllText("missions2.json", json) Here's the Mission class Serializable public enum MissionState NotStarted, OnGoing, Finished Serializable public enum MissionType Main, Sideline Serializable public class Mission public Mission() Parent 1 public int Parent get set public int Id get set public string Name get set public string Description get set public MissionState State get set public MissionType Type get set here's the output There are no exceptions thrown. The file missions2.json is created. But the data is as shown above. What is wrong that the serialization produces nothing? Thnx Matt
0
2D character controller in unity (trying to get old school platformers back) This days I'm trying to create a 2D character controller with unity (using phisics). I'm fairly new to physic engines and it is really hard to get the control feel I'm looking for. I would be really happy if anyone could suggest solution for a problem I'm finding This is my FixedUpdate right now public void FixedUpdate() Vector3 v new Vector3(0, 10000 Time.fixedDeltaTime,0) body.AddForce(v) v.y 0 if(state(MovementState.Left)) v.x walkSpeed Time.fixedDeltaTime v.x if(Mathf.Abs(v.x) gt maxWalkSpeed) v.x maxWalkSpeed else if(state(MovementState.Right)) v.x walkSpeed Time.fixedDeltaTime v.x if(Mathf.Abs(v.x) gt maxWalkSpeed) v.x maxWalkSpeed body.velocity v Debug.Log("Velocity " body.velocity) I'm trying here to just move the rigid body applying a gravity and a linear force for left and right. I have setup a physic material that makes no bouncing and 0 friction when moving and 1 friction with stand still. The main problem is that I have colliders with slopes and the velocity changes from going up (slower) , going down the slope (faster) and walk on a straight collider (normal). How could this be fixed? As you see I'm applying allways same velocity for x axis. For the player I have it setup with a sphere at feet position that is the rigidbody I'm applying forces to. Any other tip that could make my life easier with this are welcomed ). P.D. While coming home I have noticed I could solve this applying a constant force parallel to the surface the player is walking, but don't know if it is best method.
0
Process for Creating Imposters (For Unity) I'm still working on making a sports stadium with crowd etc. I've been reading a lot about 'Imposters' and 'Billboarding'. I want to explore and learn the imposters technique. But I am stuck at step 1 I have a stadium model made which is empty (no seats or people). All I want at the moment is seats. I have the model made in Maya for a seat. Do I need to make (and import to Unity) both a low poly and high poly version of the model. How exactly is an 'imposter' asset stored in data (specifically if used in Unity)? Do I need to make 2d images textures of many angles of the seat? I do have more questions, but these may be enough to get me started. Thanks as always for any help.
0
Season system Implementation system in unity So I am planning on implementing a seasons system for a 2D top down game. Each season will have a characteristic terrain feature e.g. summers will have patches of grass spread out .. which I wanna reproduce by green bloat spread around on a 2D plane or quad... These features will need to generate dynamically for every season. The implementation will be simplistic nonetheless... using green bloats for grass patches, blue bloats for waterholes.. Can you guys give me like pointers to solve this problem? Some Reference images Notice how the backdrop background changes for each season Green Patches denotes grass Light blue denotes unfrozen water, dark blue denotes frozen water These bloats are to be generated dynamically, with some conditions like frozen water and unfrozen water need to spawn next to each other Summer Season Monsoon Season Winter Season
0
How to get the tangent and normal of a collision? In my game, one of my objects casts a ray into a 2d space. If that ray were to hit another object, I'd like to draw a line that is perpendicular to the tangent of the ray's hit point. So when the ray hits the other object, a tangent is formed at the point of contact, and then I'd like to use the linerenderer component to draw a line that is perpendicular to that tangent. I already know how to use the linerenderer to draw lines, but I don't know how to get the tangent and normal from a collision. if (Input.GetMouseButton(0)) Vector2 mousePos Camera.main.ScreenToWorldPoint(Input.mousePosition) var direction (mousePos (Vector2)cueBall.position).normalized var hit Physics2D.Raycast(cueBall.position, direction, Mathf.Infinity, 1 lt lt LayerMask.NameToLayer("Ball")) if (hit) line1.SetPositions(cueBall.position, hit.point) This is the line from the cueball to the red ball. line2.SetPositions(hit.point, hit.normal) This is supposed to be the predicted trajectory of the red ball.
0
How to create rounded TV edges effect in Unity? Is there a way to get rounded TV edges like these I want rounded egdes and the distortion effect, but I can't find a way to do this. I am using Unity 2017.
0
Is Time.deltaTime different on various devices? Can someone say what is wrong with my code. I have custom timer implemented like this float timeRemain 10f void Update() timeRemain Time.deltaTime if(timeRemain lt 0) ...code here. On PC it runs like expected but on Android device timeRemain variable becomes 0 in less then 10 secs. Who can suggest me what happens when i run it on Android device?
0
Call function after Level loaded I'm stuck in this situation I have a GameObject with a script, that persist trough Level loads. Inside this script, when a condition is meet, i Load a Level, and also call a function. That function is a C Messenger Broadcast() function. The level that I am loading contain the script with the Listener for that Messenger Broadcast. The problem is that the Broadcast occurs before the level has been loaded, and so there is no Messenger Listener that can receive the event. BroadcastException Broadcasting message OnConnectionError but no listener found. I need to do the Broadcast only after the level has been loaded, but I don't know how, or maybe there is a better solution. For a simple example here is the code public class NetworkingManager MonoBehaviour void Start() DontDestroyOnLoad (this) void OnConnectionLost(BaseEvent event ) if(Application.loadedLevelName ! "LoginScreen") Application.LoadLevel ("LoginScreen") Debug.Log ("Disconnected. Reason " event.Params "reason" ) Messenger lt string gt .Broadcast ("OnConnectionError", "Disconnected")
0
How to manipulate PostProcessing effects settings during execution with c ? I need to change the intensity value of my current Vignette effect depending in specific conditions. So far I haven't been able to achieve this. Please help! Image of what I want to achieve My setup Unity 2019.3.5f1 with URP implemented Post Processing Package (v2) installed Scene with a GameObject Volume component with Vignette and Bloom effect overrides added A monobehaviour component script in the very same GameObject from above My monobehaviour script using UnityEngine using UnityEngine.Rendering.PostProcessing public class PostProcessingHandler MonoBehaviour private PostProcessVolume ppv private Vignette vignette Vignette intensity values SerializeField, Range(0f, 1f) private float lowIntensity 0.25f SerializeField, Range(0f, 1f) private float highIntensity 0.5f private void Start() ppv GetComponent lt PostProcessVolume gt () Debug.Log( ppv) When I try to retrieve PostProcessingVolume component to get it's profile (and further layer manipulation) I always get "null". Image of my setup I've seen several guides posts and even Unity documentation but I cannot get past that starting point of getting the PostProcessingVolume component, what am i missing?
0
Unity assets turned binary from text I'm working with unity and git, and for some reason, from some point the assets started being Binary files, meaning that they're not visible as normal YAML files, and I cannot see textual git diff results on them. Has anyone experiences it and knows how to revert to the textual format from the binary format?
0
Why doesn't my wave movement code account for the game object's initial position? I want an object to move like wave. Currently, when I start the game the object's position doesn't account for its initial position. How would I fix this? float amplitudeX 5.0f float amplitudeY 2.5f float omegaX 0.5f float omegaY 2.5f float index public void Update() index Time.deltaTime float x amplitudeX Mathf.Cos (omegaX index) float y Mathf.Abs (amplitudeY Mathf.Sin (omegaY index)) transform.localPosition new Vector3(x,y,0)
0
How can I change the highlighted color of a Unity button when it's clicked? I was playing around with buttons in Unity, and I wanted to see if I could change a button's highlighted color every time I clicked on it. I added a script in the same GameObject as a button component, and I had a changeColor function attached to the component's OnClick(). The function was in a ButtonScript class written like this public class ButtonScript MonoBehaviour public Button button public void changeColor() Debug.Log ("Changing highlighed color") int r Random.Range (0, 255) int g Random.Range (0, 255) int b Random.Range (0, 255) Color currentColor button.colors.highlightedColor currentColor.r r currentColor.g g currentColor.b b I couldn't do button.colors.highlightedColor new Color(r,g,b) because I got a "Consider storing the value in a temporary variable" error. When I tried a test play and clicked the button multiple times, the highlighted color didn't change. How can I make a function that changes a button's highlighted color when it's clicked, if it's possible?
0
Do I need a database to support a sign in system to associate a player with their save highscore data? I am making a 2d game with Unity, and in my game I want to add a username and a password for each player, so that when the player signs in, they will get all the data about what they played until the moment they signed in (like their highscore and so on) So my question is do I need to use a database like sqlite, or could this be done with Unity without needing an external database?
0
Unity max scene limit I want to model the earth 1 1 in unity, but I can only zoom to a certain value in the scne window of unity
0
How can i rotate the camera around an object, using compass? I want the camera to rotate around an object in Y axis, when you rotate your phone. how can i do this? i already have the code to do it using mouse, but i need it to turn with compass. here's the code for movement with mouse mouseX Input.GetAxis("Mouse X") offset (Quaternion.AngleAxis(mouseX cameraSpeed, Vector3.up) offset) transform.position point offset transform.LookAt(point) i know that setting the mouseX value to change with compass direction is my answer, but how can i do it?
0
Unity UV map, tint change color of texture I have an array of vertices with texture coordinates for a UV map in Unity newUV.Add(new Vector2 (0, 1)) FACE 1 newUV.Add(new Vector2 (1, 1)) newUV.Add(new Vector2 (1, 0)) newUV.Add(new Vector2 (0, 0)) newUV.Add(new Vector2 (0, 1)) FACE 2 newUV.Add(new Vector2 (1, 1)) newUV.Add(new Vector2 (1, 0)) newUV.Add(new Vector2 (0, 0)) mesh.uv newUV.ToArray() It textures my mesh just fine. How could I go around tinting FACE 1 to a darker color? Let's say the texture is just plain green and I wanted to texture only on FACE 1 to be a darker shade of green.
0
Food Game using Online Searchs I am thinking of making a simple game with Unity. The aim would be to keep a person healthy by feeding it well balanced food and drinks. Rather than hard codding every single type of food or drink I can think of I was thinking of letting the player choose any type of food he wants and then screen the internet for it's calorific value, saturated fat, sugars etc ... This would make the game much more enjoyable than being limited by the foods I can think of. I was wondering how you would go about doing that ? Could I use an API to extract data from google or wikipedia. I noticed that when you type " food calories" in Google you get a return from the Wikipedia page like this Obviously, there is a way of extracting the data from Wikipedia and I could automate the searchs by taking the player's entry as a string and running a search with it. How would one recommend going about this ? Also, is it safe ? Thanks
0
Can an iOS application have an explicit quit button? I've heard a rumor that you cannot have an explicit quit button on your app when it goes to the Apple App Store, can anyone verify this? It seems that most applications do not have one, and there is no explicit quit. How to developers handle quitting in general on iOS applications? Note I am using Unity, C , and Xcode to develop my game for the iPad.
0
How to make a car move sharper at high speed? I am working on a car racing game on Unity 2018.1. My car works perfectly at low speed but as it speeds up, I lose control over the car and it starts to drift independently. What can I do to prevent this?
0
Add object to a Terrain? It's possible to add object made by blender to unity terrain ? this object will become a part of it. I can add grass and trees on it.
0
How to achieve lighting like this in Unity for 2D games? How could I accomplish a lighting effect something similar to this game? I'm not talking about the shadows but about the glowing lighting effect on the crystals and the torches. Anyone got any clues? More images from the games steam page
0
Are all referenced sprites loaded into memory for each object? I'm trying to understand how Unity works behind the scenes. Let's say I have a GameObject that has a large number of sprites attached to it in an array (think a deck of cards). Each GameObject represents 1 card. For simplicity, each card has all the sprites for all the card faces. So it has 52 sprites 1 for the card back (all in a sprite sheet of course). If I have all 52 cards placed in the world. Does this mean I have 53 52 2756 sprites, or is there only one instance of each sprite that's being displayed (ie does it only use the resources of 52 active sprites)? I guess what i'm asking is if I have a bunch of sprites attached to a GameObject, are they all instantiated when the object is created, or are they only created when they are actually attached to the sprite renderer? Would it be more efficient to only attach the current cards value sprite (ie just the back and the face for the cards value)?
0
Unity 2D launch player towards mouse location few notes I'm new to game development I'm not new to developing (1 year of front end web development) I'm trying to get my character to launch towards mouse left click button (which I understood to be translated into screen onclick once its exported to mobile) I've got the following code down (used the web for help) move speed is a float that's equal to 10 in this example if (Input.GetMouseButton (0)) mousePosition Camera.main.ScreenToWorldPoint (Input.mousePosition) direction (mousePosition transform.position).normalized rb.velocity new Vector2 (direction.x moveSpeed, direction.y moveSpeed) Which works great, but has 2 issues If I keep holding leftMouseButton my character is pinned to the cursor I want a single, gravity affected, launch (jump of sort) towards my mouse button. This is all under the Update() function.
0
Simulating an aging population Introduction The main idea is to "classify population as they age". Let me further explain it with an example Example There are 50k population (we are not going to care about if male or female for now). Inside these number there are kids 0 16 , fertile 16 40 , non fertile 40 100 . Question Which would be a nice implementation to represent an evolving population data that is better or at least not too resource intensive as my example below? My Idea (Pseudo code) Population Array Age 0 gt 5 Array a pop obj that stores data Age 5 gt 10 pop obj . . . Age 95 100 pop obj This would be the structure and each tick happens this calculation FertilePop.count fertility rate (some other stuff) numberOfBirths where numberOfBirths are added to the Age 0 5 .obj.count and the rest of Age rang are subtracted a number and added onto the next Age rang until Age 95 100 where they "die of old age". Notes This is purely background data and i am asking for a better solution implementation that could be less complex, more dynamic and learn from it. I expect to be able to do a graph plot so the user sees the pop evolution. I took my interest in the matter from this link here to a population simulator. https niko.roorda.nu computer programs popsim population simulation Thanks for your interest in this question.
0
Get all objects of Additively loaded Scene? (LoadSceneMode.Additive) I learned how to Load and unload scenes in unity. using LoadSceneMode.Additive. I like to spit up my scenes as much as possible and retain the stuff I need as I go along. I'd like to be able to find all objects loaded from a specific scene. Obviously Unity knows but I can't find how to get them. For now, my workaround is to put them in a specifically named empty or have them tagged in a certain way, but that is a workaround. Is there an easier way?
0
Check which Player got highest Number from Dice I am doing a Ludo Game and currently i need to check which Player got the Highest Number from the Dice and the player which has the highest number goes on the starting position. Currently i created this method to check which player got the highest number then the player which has the highest numbers runs the method MovePlayer() public void FirstTurn() player1Steps GameObject.Find("Player1").GetComponent lt LevelManager gt ().randomNumberSteps player2Steps GameObject.Find("Player2").GetComponent lt LevelManager gt ().randomNumberSteps if(NetworkManager.MyGamePlayerId "Player1" amp amp player2Played true) MovePlayer() else if(NetworkManager.MyGamePlayerId "Player2" amp amp player1Played true) if(player2Steps gt player1Steps) MovePlayer() I am using the Photon Cloud Service since this is a multiplayer Game Thanks
0
Check if all gameobjects are destroyed I am making a shooting game, where I have a countdown as I destroy enemies. I want to implement logic when all the game objects are destroyed within the given time, and the countdown reaches zero. How do I do that?
0
How do I keep vertex position when changing material? I've created 2 shaders using shader graph which I'm applying to a sphere to simulate a ball of water ice. The water shader distorts the shape of the sphere over time to look like it's flowing a bit. What I would like to do is swap the shader from water to ice, and keep the shape of the distorted sphere when the materials swap over. I'm pretty new to unity and shaders in general so I don't know where to start.
0
2 D character not falling to the ground I am very new to Game Development and I am making a game with a simple Ragdoll which has a body, a head, and 2 limbs(hands). The head and the limbs are hinged to the body and I have kept the Ragdoll above a cube to be used as the ground on which the Ragdoll falls. Till now, I haven't added any scripts for movement or anything, I just want my Ragdoll to fall on the cube below it properly. But when I click play, the Ragdoll just starts to float above its original position. When I move it through the editor away from the cube(ground), it does fall down. It's like the cube is opposing the downward acceleration of the Ragdoll. The Ragdoll won't land on the cube. All the bodies have Rigid body and collider scripts. The Ragdoll also doesn't disassemble, it manages to keep itself together. Can someone please tell me what I am doing wrong. I researched about this but I have found no solution. I am using the free version of Unity.
0
Jumping onto higher ground Collider issues What's the general solution to the following character animation problem (I'm using Unity)? You have a character with a capsule collider and a jump animation that allows you to jump onto higher ground (such s boxes, etc.). The character shouldn't be able to jump unrealistically high so she goes into a crouched posture while in the air and the collider is scaled accordingly in an animation curve. However when the character jumps onto the box to land, the character animation (and collider) want to extend back to wards the ground but there is not enough space and either collision detection fails and the character falls into the geometry or the collider starts a collision fight with the box and keeps bumping up and down, keeping the character in an airborne state. Please see screenshots to get a better idea... What would be a good way to work around this problem?
0
Stopping player from spamming movement keys which causes glitches Unity C I wrote a script for the player movement in c . Whenever the player presses A or D, it moves him her to the left or right by 12 units and when the player presses W or S, it moves him her up or down by 12 units. My script works fine, but if a person starts to spam all of the keys at once, it glitches out and the player object is not in line with the level anymore. I want to have the script check if there a movement is currently happening before executing the movement on the keypress. Here is my script void Update () transform.Translate(Vector3.forward ForwardSpeed Time.deltaTime) if (Input.GetKeyDown (KeyCode.A) amp amp side gt maxSideLeft) MoveObjectTo(this.transform, new Vector3(this.transform.position.x 12, this.transform.position.y, this.transform.position.z 10), movementSpeed) side 1 else if (Input.GetKeyDown (KeyCode.D) amp amp side lt maxSideRight) MoveObjectTo(this.transform, new Vector3(this.transform.position.x 12, this.transform.position.y, this.transform.position.z 10), movementSpeed) side 1 if (Input.GetKeyDown (KeyCode.W) amp amp level lt maxLevelHeight) MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y 12, this.transform.position.z 10), movementSpeed) level 1 else if (Input.GetKeyDown (KeyCode.S) amp amp level gt minLevelHeight) MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y 12, this.transform.position.z 10), movementSpeed) level 1 if (Input.GetKeyDown (KeyCode.R) Input.GetKeyDown(KeyCode.Space)) SceneManager.LoadScene ("Scene1") Time.timeScale 1 private void MoveObjectTo(Transform objectToMove, Vector3 targetPosition, float moveSpeed) StopCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed)) StartCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed)) public static IEnumerator MoveObject(Transform objectToMove, Vector3 targetPosition, float moveSpeed) float currentProgress 0 Vector3 cashedObjectPosition objectToMove.transform.position while (currentProgress lt 1) currentProgress moveSpeed Time.deltaTime objectToMove.position Vector3.Lerp(cashedObjectPosition, targetPosition, currentProgress) yield return null
0
Redundant checks from spatial partitioning A simple 2D grid partition system for collision detection divides space into equal sized tiles. Colliders then map themselves to tiles with their bounding box in O(1) time. Collision detection only has to be performed between objects that occupy the same tile(s). Collision detection is expensive so the more culled, the better. With a grid partitioning system, how are collisions culled when colliders share multiple tiles? For example, Circle A and Circle B both sit on the edge between Tile 1 and Tile 2. Iterating both tiles would make collision detection between Circle A amp Circle B run twice. A global pair hashtable seems performance expensive since it has to be cleared every frame. Tracking pairs inside colliders takes a lot of memory. How do you mitigate redundant pairs when iterating through partition grid tiles?
0
Lock mouse in center of screen, and still use to move camera Unity I am making a program from 1st person point of view. I would like the camera to be moved using the mouse, preferably using simple code, like from XNA var center this.Window.ClientBounds MouseState newState Mouse.GetState() if (Keyboard.GetState().IsKeyUp(Keys.Escape)) Mouse.SetPosition((int)center.X, (int)center.Y) camera.Rotation (newState.X center.X) 0.005f camera.UpDown (newState.Y center.Y) 0.005f Is there any code that lets me do this in Unity, since Unity does not support XNA, I need a new library to use, and a new way to collect this input. this is also a little tougher, since I want one object to go up and down based on if you move it the mouse up and down, and another object to be the one turning left and right. I am also very concerned about clamping the mouse to the center of the screen, since you will be selecting items, and it is easiest to have a simple cross hairs in the center of the screen for this purpose. Here is the code I am using to move right now using UnityEngine using System.Collections AddComponentMenu("Camera Control Mouse Look") public class MouseLook MonoBehaviour public enum RotationAxes MouseXAndY 0, MouseX 1, MouseY 2 public RotationAxes axes RotationAxes.MouseXAndY public float sensitivityX 15F public float sensitivityY 15F public float minimumX 360F public float maximumX 360F public float minimumY 60F public float maximumY 60F float rotationY 0F void Update () if (axes RotationAxes.MouseXAndY) float rotationX transform.localEulerAngles.y Input.GetAxis("Mouse X") sensitivityX rotationY Input.GetAxis("Mouse Y") sensitivityY rotationY Mathf.Clamp (rotationY, minimumY, maximumY) transform.localEulerAngles new Vector3( rotationY, rotationX, 0) else if (axes RotationAxes.MouseX) transform.Rotate(0, Input.GetAxis("Mouse X") sensitivityX, 0) else rotationY Input.GetAxis("Mouse Y") sensitivityY rotationY Mathf.Clamp (rotationY, minimumY, maximumY) transform.localEulerAngles new Vector3( rotationY, transform.localEulerAngles.y, 0) while (Input.GetKeyDown(KeyCode.Space) true) Screen.lockCursor true void Start () Make the rigid body not change rotation if (GetComponent lt Rigidbody gt ()) GetComponent lt Rigidbody gt ().freezeRotation true This code does everything except lock the mouse to the center of the screen. Screen.lockCursor true does not work though, since then the camera no longer moves, and the cursor does not allow you to click anything else either.
0
Unity Odd distortion on default material cube Does anyone know what causes this strange effect that looks like ripples? This is simply the default material on a cube and should be perfectly smooth. (Clear example at top right of image) Another example
0
Unity font API behaves differently in built game Specifically it's Font.CreateDynamicFontFromOSFont(), use this script attached to an empty GameObject in the scene. using System.Collections using System.Collections.Generic using UnityEngine public class TestFontTexture MonoBehaviour void Start () var font Font.CreateDynamicFontFromOSFont("Consolas", 12) font.RequestCharactersInTexture("HelloWorld", 20) SaveTexture2PNG(". fontTexture.png", (Texture2D)font.material.mainTexture) void Update () void SaveTexture2PNG(string path, Texture2D tex) byte bytes tex.EncodeToPNG() System.IO.File.WriteAllBytes(path, bytes) After click play it should create a fontTexture.png file containing character glyphs in the Assets folder, but only in editor though. In the built game it just created a completely black image. Since it's OS concerned, I'm using Windows 7 with font Consolas installed and Unity 5.6.5f. How to make it work in a built game?
0
How to only allow one space in an InputField? I've been messing with this for a while now and I can't get this to work 100 . I'm using an InputField for players to enter a character name, and I want to allow a first and last name. Here's how I've been trying this private void CharNameRestrictions() Debug.Log(spaceCount) if (Input.GetKeyUp(KeyCode.Space)) spaceCount if (spaceCount gt 1) spaceCount 1 playerNameInput.text playerNameInput.text.Remove(playerNameInput.text.Length 1) if (!(playerNameInput.text.Contains(" "))) spaceCount 0 if (playerNameInput.text.Length gt 15) playerNameInput.text playerNameInput.text.Remove(playerNameInput.text.Length 1) This sort of works, but if you press and hold space while typing another character, it still lets you add additional spaces. Is there a way to simply ignore the space keycode when there is already a space in the field?
0
Unity Debug UnityGfxDeviceWorker (34) EXC RESOURCE RESOURCE TYPE MEMORY Unity How does one debug this Xcode error on an iOS device? Debug UnityGfxDeviceWorker (34) EXC RESOURCE RESOURCE TYPE MEMORY
0
AddRelativeForce not working correctly I am stuck on the code for couple of days but couldn't figure it out. Therefore I turned out to look the answer here but couldn't find any that match the requirement Hope some One might help here is the code Part1 Step Horizontal Movement Use to get left and right movement if(Input.GetKey ("right") Input.GetKey ("left")) moveDir.x Input.GetAxis("Horizontal") get result of AD keys in X rigidbody.velocity moveDir speed Part2 Continuse Forward Movement if (Input.GetKey(KeyCode.UpArrow) Input.GetKey(KeyCode.W)) moveDir.z Input.GetAxis("Vertical") rigidbody.AddRelativeForce(moveDir 50) I have a Cube with added rigidBody Component. When pressed left or right key the cube should move in that direction and when key is released it should stop Part one when run commenting part2 code runs correctly the other movement that I am trying to achieve is the cube should move continuously.But the thing is when pressed up key it should increase the magnitude and when released it should maintain the magnitude and move constantly.This is also achieved successfull with the part2 code by commenting part1 code But when but run without commenting any of them part1 results are correct but part2 does not provide correct result which was obtained by commenting part1 code Is there any other way to obtain the same reult
0
How to check audio quality after changing import settings I have changed the quality of an audio clip from 100 to 10 in the import settings. But when I played the clip from the inspector, I didn't hear any noticeable difference The compression format of the audio clip is set to 'Vorbis' So I wonder if it's the original file or the compressed file that is being played by the Unity Editor?
0
Follow Camera to Two objects at different time I am developing simple 2D game in unity. I am locked with the camera movement for last two days. I've camera script that is working as follows Follow the player to X and Y direction If player stops moving, Camera must find the nearest enemy and should move to that direction Both of the above function works fine, but separately. Camera finds and follows the enemy, when there is no input from player for last 10 seconds. But after few seconds (When stops following enemy), Camera retains the player's position. That creates unlikely effect in the scene. I want the camera to have a last position and started following player from there. For your reference I'm writing my Camera Script. public class MultipleTargetCamera MonoBehaviour public List lt Transform gt targets ReadOnly public GameObject closestEnemy null public EnemyController closestEnemyController null public Vector3 offset public float smoothTime 0.5f private Vector3 velocity Vector3 camPosition Update is called once per frame void LateUpdate() if (targets.Count 0) return if (!TheGlobals.instance.movingTowardsEnemy) MoveCamera() else MoveAsEnemy() void MoveAsEnemy() camPosition new Vector3(transform.position.x closestEnemyController.xDiff, transform.position.x closestEnemyController.yDiff, transform.position.z) transform.position Vector3.SmoothDamp(transform.position, camPosition, ref velocity, smoothTime) void MoveCamera() Vector3 centerPoint GetCenterPoint() Vector3 newPosition centerPoint offset transform.position Vector3.SmoothDamp(transform.position, newPosition, ref velocity, smoothTime) Vector3 GetCenterPoint() Vector3 targetPos new Vector3(targets 0 .position.x, targets 0 .position.y, transform.position.z) if(targets.Count 1) return targetPos var bounds new Bounds(new Vector3(targets 0 .position.x, targets 0 .position.y, transform.position.z), Vector3.zero) for(int i 0 i lt targets.Count i ) bounds.Encapsulate(new Vector3(targets i .position.x, targets i .position.y, transform.position.z)) return bounds.center public void FindNearestEnemy() GameObject gos gos GameObject.FindGameObjectsWithTag("Enemy") float distance Mathf.Infinity Vector3 position transform.position foreach (GameObject go in gos) Vector3 diff go.transform.position position float curDistance diff.sqrMagnitude if (curDistance lt distance) closestEnemy go distance curDistance closestEnemyController closestEnemy.GetComponent lt EnemyController gt () targets 0 .parent this.transform StartCoroutine(StopMovingTowardsEnemy()) IEnumerator StopMovingTowardsEnemy() yield return new WaitForSeconds(0.01f) TheGlobals.instance.movingTowardsEnemy false I hope I did explain well. Looking for the answer. Thank you in advance!
0
Why does the player grab the object outside the trigger zone? I want the player to be able to grab an object (in this case the knife) when he is in the object's trigger zone. He can get the knife but there is a problem if I press grab button outside of the trigger zone, then he can get the knife immediately after entering the zone. I want Unity to get the input only when the player is in the trigger, otherwise it should not be working. Here's the grab script using System.Collections using System.Collections.Generic using UnityEngine public class Grab MonoBehaviour public GameObject player private bool grabbed public GameObject knifePosition private bool isInTrigger void Update() if (Input.GetButtonDown( quot Grab quot )) grabbed true else grabbed false if (grabbed amp amp isInTrigger) gameObject.transform.position knifePosition.transform.position private void OnTriggerEnter2D(Collider2D collision) if (collision.gameObject player amp amp grabbed) gameObject.transform.SetParent(player.transform) isInTrigger true Debug.Log( quot Picked up quot )
0
"SetSelectedGameobject" only highlights button on second try (Unity 2017.3) To support the use of a gamepad in the options menu I set SetSelectedGameObject and firstSelectedGameObject (which doesn't seem to do anything) to the button in the upper left, so it's highlighted. This works fine in my pause and option menus (panels that are enabled disabled) but there's also a third panel that displays the controls as an image. On this screen the first button is set as selected but it doesn't get highlighted until I go back to the pause menu and then open the "controls" screen again. The Hierarchy The ControlsPanel looks like this click All 4 buttons are set to "automatic" and they're all accessible to the gamepad but, like I said, the first one ("Keyboard") doesn't light up the very first time I access the panel. It should be like this Click on "Controls" in the pause menu ControlsPanel is enabled "Keyboard" button is highlighted Pressing right on the gamepad highlights the next button ("Controller") What actually happens Click on "Controls" in the pause menu ControlsPanel is enabled "Keyboard" button is still grey Pressing right on the gamepad highlights the next button ("Controller") Press the "Back" button ("ControlsPanel" is disabled and "PausePanel" enabled) Click on "Controls" again This time the "Keyboard" button is highlighted The "ControlsPanel" script public Image pic public GameObject controllerChoicePanel public GameObject firstControls private String controls private bool windows void Start() controls GetControls() windows GetOS() pic.sprite Resources.Load lt Sprite gt (controls) if(windows) controllerChoicePanel.SetActive(true) EventSystem es EventSystem.current es.firstSelectedGameObject firstControls es.SetSelectedGameObject(firstControls) Any idea why it would work fine in my pause options menu but not in the "Controls" one, even though I'm doing the same thing?
0
Player rotation issues (Player returns to default forward rotation after releasing keys) So basically what is happening is that my player rotates and faces the direction that he is currently being steered toward (which is wonderful). But after I release, let's say the A key, meaning he is currently facing and moving to the left, he goes back to facing forward after the key is released. Here is my code public class PlayerMovement MonoBehaviour public bool isGrounded private float distToGround private Vector3 v private Vector3 h public float speed Rigidbody rb Collider col void Start() rb GetComponent lt Rigidbody gt () col GetComponent lt Collider gt () distToGround col.bounds.extents.y void Update() if (Physics.Raycast (transform.position, Vector3.up, distToGround 0.1f)) isGrounded true else isGrounded false if (isGrounded) v new Vector3(0, 0, Input.GetAxis("Vertical")) speed h new Vector3(Input.GetAxis("Horizontal"), 0, 0) speed rb.MovePosition(rb.position v Time.deltaTime) rb.MovePosition(rb.position h Time.deltaTime) This deals with all the rotation Vector3 direction new Vector3( Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical") ) Quaternion rotation Quaternion.LookRotation(direction, Vector3.up) transform.rotation rotation I obviously know that the reason this is happening is because the rotation is being set to the axis currently being pressed, so when I release any key, the rotation goes back to the original position. I just can't quite figure out how to fix it...
0
Could use some help figuring out bouncy physics material in this PhotonEngine game So I'm trying to prototype a primitive 1v1 fighting game where the goal is to push the opponent off of the platform rather than actually fight. This is working great in a local multiplayer setup using a physics material on the "belly" of the Rigidbody2d players (the circle collider gameobject nested inside of the square gameobject has the bouncy material). But I'm toying with the idea of making it a network game and it seems the physics material doesn't get communicated too well over the Photon Realtime connections? Here is a video showing how it seems like sometimes the position is updated but sometimes a player runs into another player and its like a brick wall https imgur.com QYWH178 Any ideas of what to try or if this is even possible? A bit about how things are currently setup Each player object has the nested collider with a high bounciness material on it. Each player moves via the Rigidbody2D component via .AddForce(direction Speed) I have a Photon View component on the player prefab and a Photon Rigibody 2D View component that is checked to Synchronize Velocity and Angular Velocity, as well as a Photon Transform View component synchronizing Position. Both the transform view and Rigidbody2dView are Observed Components in the Photon View. I also found a script someone posted where they were manually sending the position velocity data via OnPhotonSerializeView() I've tried adding that script and making that observable as well, but no luck, but it looks something like this public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.IsWriting) We own this player send the others our data stream.SendNext(transform.position) stream.SendNext(transform.rotation) stream.SendNext(r.velocity) stream.SendNext(r.angularVelocity) else Network player, receive data latestPos (Vector3)stream.ReceiveNext() latestRot (Quaternion)stream.ReceiveNext() velocity (Vector2)stream.ReceiveNext() angularVelocity (float)stream.ReceiveNext() valuesReceived true Update is called once per frame void Update() if (!photonView.IsMine amp amp valuesReceived) Update Object position and Rigidbody parameters transform.position Vector3.Lerp(transform.position, latestPos, Time.deltaTime 5) transform.rotation Quaternion.Lerp(transform.rotation, latestRot, Time.deltaTime 5) r.velocity velocity r.angularVelocity angularVelocity
0
Using raycast to detect whether a wall immediately blocks a player in Unity C I am working on a game project of which involves a procedurally generated maze. Within this maze, there are different types of tiles, such as walls and gates. I want to program the player so that it cannot move through a tile that is tagged as a "wall", and I am hoping to use ray casting to detect item tags. Now, you may think it would be simpler to use rigid bodies, but the game is set up so that the player moves 1 unit per movement, instead of being able to move at any randomly input distance, in order to keep the game adhering to a "grid" for the sake of other events that happen within the game. So, for this reason, i wish to detect if a wall is north of the player (let's call "north" as "up", as I have an "up blocked" boolean to state if a wall is directly "north" of the player) but, my code doesn't always recognise walls that are immediately north of the player, and instead sometimes the "up blocked" boolean becomes activated as "true" when a wall is left, right, or "below" (down) of the player, irrespective of whether or not there is a wall "above" or down. here is my code Vector2 vUp new Vector2(transform.position.x, (transform.position.y 0.05f)) RaycastHit2D hitUp Physics2D.Raycast(transform.position, vUp) if (hitUp.collider ! null amp amp hitUp.collider.tag "wall") upBlocked true else upBlocked false I have spent many hours looking for a solution for this problem, but most mediums provide information that either didn't work, wasn't applicable or simply was grossly out of date.
0
Problem with Raycasting in a 2D Game I'm new to using unity and came across a problem when I was following a tutorial. The game is in two dimensional space, and when my player walks over a certain tile the detection never goes off. Here's the code that I have, function calculateWalk() yield WaitForSeconds(0.3) var hit RaycastHit if(Physics.Raycast (transform.position, Vector3.down, 100.0)) Never evaluates to being true var distanceToGround hit.distance Debug.Log("Hit") if(hit.collider.gameObject.tag "tallGrass") walkCounter Debug.Log("Tall Grass") END if END if END calculateWalk() I've made sure to attach the script to my player, as well as tag the tiles that I want with "tallGrass". I've followed what was done in the tutorial, but for some reason it's not working out for me, not sure if this is all the code needed to help solve this problem, if more information is needed let me know, I also set my player 1 unit above the tiles.
0
timeScale 0 doesnt stop all prefabs in unity As expected timeScale 0 can be used for stopping the game or pausing but when i make timeScale equal to 0 some prefabs still move and they can shoot bullets but addforce doesnt effect to bullets and they stop there. I know i can fix the problem on handling code of my prefabs but they are a lot. is there a good way to do the trick in my game? thank you for helping
0
Split a region into arrays based on point region I have an array of points forming a grid. I want to split this array into multiple arrays that each contain a region of point. Let's say each point as a value like on this image The points having the same value and being connected would go into the same array. If it was only an array of all the 8 or all the 7, it wou d be easy, but in thsi case I need the arrays to contain connected equal values. For example, the purple region of 1 would make an array, the 8 region on the left would make an array and the one on the right too, but a different one. I just don't know how to use a loop to navigate in the grid and affect each point to an array based on they relation with other points of the same value. As this is the objective, think of the values as biome that I want to assign to an array.
0
2D player controller moves to the left, but not to the right I wrote a C script to control a 2D player, but the script is not fully working. When I press the right arrow d key to move the player is not moving in the right direction, but I have done the same exact thing for left key which works fine.The script shows no errors too.Kindly help me to solve the issue.The code is using UnityEngine public class PlayerController MonoBehaviour SerializeField private Rigidbody2D rb2d SerializeField private float speed SerializeField private float jump private static float tempspeed private static float tempjump private bool isRight private bool isLeft private bool isSpace private void Start() isLeft false isRight false isSpace false speed 5f jump 7f tempjump jump tempspeed speed private void Update() ReadInput() private void FixedUpdate() Move() private void ReadInput() if (UnityEngine.Input.GetKey("d") UnityEngine.Input.GetKey("right")) isRight true else isRight false if (UnityEngine.Input.GetKey("a") UnityEngine.Input.GetKey("left")) isLeft true else isLeft false if (UnityEngine.Input.GetKey("w") UnityEngine.Input.GetKey("up")) isSpace true else isSpace false private void Move() Vector2 speedVectorRight new Vector2( tempspeed, rb2d.velocity.y) Vector2 speedVectorLeft new Vector2( tempspeed, rb2d.velocity.y) Vector2 jumpVector new Vector2( rb2d.velocity.x, tempjump) if ( isRight) rb2d.velocity speedVectorRight else speedVectorRight.x 0f rb2d.velocity speedVectorRight if ( isLeft) rb2d.velocity speedVectorLeft else speedVectorLeft.x 0f rb2d.velocity speedVectorLeft if ( isSpace) rb2d.velocity jumpVector When I tried to print debug statements in different parts of if statements, they work fine. The problem in my observation is in if ( isRight) rb2d.velocity speedVectorRight else speedVectorRight.x 0f rb2d.velocity speedVectorRight The rb2.velocity is not accepting speedVectorRight I guess.Thanks in advance!
0
How can I disallow the changing of a parent? I want to disable transform.SetParent(Transform) for a particular GameObject. I am not sure where to start, so it is really difficult to show what I have tried. Is this even possible?
0
Make a platform appear and disappear constantly I am building a platformer. In this game, I need one of my platforms to constantly activate and deactivate. Here is how I have tried to code this so far, but it causes Unity to freeze void Update() for (i 0 i lt 2 i ) platform.SetActive (false) if (i gt 1 ) i platform.SetActive (true)
0
How to properly copy paste object between folder? I'm new to unity and found some simple task can't be done here. For example in projects tab, i want to copy paste a script from script folder to other folder. I should be able to simply select the script, press ctrl C , go to target folder , press ctrl V to paste but nothing happen. So for now , i have to duplicate it then move it to new folder then rename it. But why can't i do simply copy and paste ?
0
Prevent showing movie files after packaging unreal game I developed a game which has some videos inside it. I added videos into my project folder so that I can access them. After packaging, on the folder all videos will be shown as its original format which everyone can play it. How is it possible on release version no one can go to game folder and play it? Maybe some kind of encryption or change format of file which only its game can play it would help it. For example when you have a game on your computer, the only way to see the video is that you play the game and you will see relevant videos in the right time. However, after packaging, all videos will be on a folder any everyone can go to the folder and play it and see videos even without playing game. In Unity after releasing the game, you can't access assets, it will be shown in a file with .resource extension so no one can access it. However, in Unreal Engine, it will show the real file.
0
how to recieve a trigger with collider or recieve a trigger with collider in unity i know if your object has a Collider you can sense another Collider with OnCollisionEnter function or... and you can sense another collider with trigger with OncollsionEnter function and... but i want to sense other object with trigger even with collider or even with trigger. i cant sense otherobjects that have triggers. for example i have bullet that as i dont want to collider have any physics i turned it to trigger but how can make a charcter to sense it? Thank you for helping
0
(2D) Take player speed into account while shooting bullets In my top down 2D game, there is a plane as shown below The plane shoots bullets forward. For firing bullets, I use obj.GetComponent lt Rigidbody2D gt ().AddForce(transform.up 500) However, when player presses up arrow or A key, plane speed increases. At this point, bullets are slower than the plane and appear to move backwards when plane moves at maximum speed. How do I take into account player speed so that force applied takes into account player speed?
0
How to mark a variable as prefab independent? I am making a game that has a symmetrical level design. Each player own a portion of the map and each portion is the same. As such, I placed the portion as a prefab so that when I apply the prefab, every other portion gets changed as well. On the prefab there is a script. This script contains a variable called playerId. I dont want this variable to change to prefab default when I apply the prefab. Is there an attribute tag I can use to do this? As far as I am aware, Unity's transform.position doesnt get affected by the prefab defaults.
0
No intellisense on my classes I've been using Monodevelop's current version and Unity 4. I don't get intellisense on the classes I've created but I do have intellisense on classes that are in Unity's framework. Bug or its just as it is? I use UnityScript class SomeClass extends ScriptableObject public function Test() return "" In another class, when I use a variable typed as this class I get no intellisense.
0
Using AR measuring techniques to allow free movement in a VR room I am a Game Design student currently working on my graduation project. For this project, I want to develop a VR room, which can be walked through freely by using a smartphone. I already made a 1 1 scale replica of a meeting room (in Unity 3D) in the office I am currently working. So I have been exploring different technologies that allow distance measuring techniques using markers and AR applications to measure distance between physical objects. for example https www.youtube.com watch?v Tk31uGo7xHo https www.ourtechart.com augmented reality augmented reality tutorial 47 shapes combined trackers unity3d vuforia Now is it possible to use these methods to translate the measured distance into a vector 3 movement in a VR room? Also, is this relatively easy to do for a beginner programmer? To be clear The goal is to allow free movement through a pre built 1 1 scale 3D room in VR by using a smartphone and markers in the physical room. Which hopefully will create some cool VR experience for the players. Could anyone give me some advice? For example is there anyone who already tackled this problem and is willing to share knowledge with me? Thanks in advance
0
Mechanim "Hand Closing Opening" Animation control with trigger I wish to control any given Animator state "Playhead", with a variable rather than have it play automatically with time. This is for an animation of a hand making a "clench gesture" which will be bound to an analog controller trigger output value. I have considered the following Inside StateMachineBehaviour.OnStateUpdate method (State machine behavior script attached to a state in the Mechanim graph) Call Animator.Play or Animator.CrossFade to play a given clip from a given time with speed set to 0. This should get called every update while in the state. The issue with this is that the whole state will stop, then start again which means OnStateEnter and OnStateExit continually fire, rather than just the OnStateUpdate method to control the "Playhead". Animator.ForceStateNormalizedTime(time) This would be fine but it has been depreciated. Use timers and the Animator speed variable to calculate when to toggle playing a clip at a certain speed such to match the displacement of the trigger. Seems the wrong way to go about it. Use the legacy animation system This works fine but you don't get the perks of Mechanim FSM eg. blend trees. Since Unity seem to have removed the ability to manipulate the time of a running clip or Mechanim state, it makes me think it's something I shouldn't be doing. Am I going about this the wrong way? Why does it seem difficult to play an animation via something other than the time domain?
0
2d raycast collision problem I am currently making a 2d top down game in unity and have stumbled upon a problem with my raycast collision. I want my green player to stop moving when colliding with a wall, therefore i made my player object cast a ray in the direction it is moving. Its velocity is nullified when the distance to the collision point is equal to zero, or below. What seems to be the case is that the player object stops moving way to late and ends up overlapping the wall object. I tried to make an offset such that the player stopped a bit earlier, but it seems that the offset needs to differ depending on the side of the wall block. It even feels like the point at where the player stops is arbitrary and differs from time to time. I would really like to know why this happens and what i can do to fix it. BTW, I would also really like to be able to change the players speed and still have it work. Here are some pictures of my problem The code i use for the player using UnityEngine using System.Collections public class Player MonoBehaviour SerializeField private float speed Rigidbody2D body bool justChangedDir Vector2 moveDir void Start() body GetComponent lt Rigidbody2D gt () void MoveDirection() Vector2 input new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) if ((input.x ! 0 amp amp input.y 0) (input.x 0 amp amp input.y ! 0)) justChangedDir false if (moveDir.x ! 0) moveDir new Vector2(input.x, 0) if (input.y ! 0 amp amp !justChangedDir) moveDir new Vector2(0, input.y) justChangedDir true else if (moveDir.y ! 0) moveDir new Vector2(0, input.y) if (input.x ! 0 amp amp !justChangedDir) moveDir new Vector2(input.x, 0) justChangedDir true else moveDir input void CheckCollision() RaycastHit2D hit new RaycastHit2D() if (moveDir.x ! 0) hit Physics2D.Raycast(body.position, Vector2.right moveDir.x, 1) Debug.DrawRay(body.position, Vector2.right moveDir.x, Color.yellow) else if (moveDir.y ! 0) hit Physics2D.Raycast(body.position, Vector2.up moveDir.y, 1) Debug.DrawRay(body.position, Vector2.up moveDir.y, Color.yellow) if (hit.collider ! null amp amp hit.distance lt 0.5 ) body.velocity Vector2.zero else body.velocity moveDir speed Update is called once per frame void Update() MoveDirection() if (moveDir ! Vector2.zero) CheckCollision() else body.velocity Vector2.zero Any help will be really appreciated ) Many thanks in advance! Gusgus
0
Code for making Material offset follow Bone transform not exactly working In my game, I have an Eye Bone that is constantly moving. I'm trying to make a material attached to the eye (pupil material) move in relation to the Eye bone's transform. This Script is indeed moving the Material's offset, but it is seemingly ignoring the offsetMultiplier bit. For instance, if I set offsetMultiplier to 0, the material offset never equals 0 but instead keeps exactly following the Bone transform numbers. What might be the mistake here? using System.Collections using System.Collections.Generic using UnityEngine public class EyeBoneMatOffset MonoBehaviour public Transform targetBone public Material mat public float offsetMultiplier 0.0f 0 for testing purposes Start is called before the first frame update void Start() Update is called once per frame void Update() Create a vector to offset the material var offset new Vector2(targetBone.transform.localRotation.eulerAngles.x offsetMultiplier, targetBone.transform.localRotation.eulerAngles.y offsetMultiplier) Apply the offset mat.mainTextureOffset offset Script inspector set up Edit I'm having issues getting the Eye(Pupil) Material to correctly move with the Eye bone movement. You can see that when I hit play, the script does get the Eye Material to Initially move, but then it is (visually) frozen instead of moving back and forth. The goal is for it to correctly Eye Track the cube. As a sidenote, for the Eye Material's X and Y offset, the visually correct range of its pupil movement is 0.45 to 0.45 (X), and 0.45 to 0.45 (Y). So it's weird to me that the X and Y offset of the Eye Materials are shown to be moving within that range (which should be good!), yet are not actually moving visually except for when the game first starts.
0
Unity baked lighting blotchy shadows, bleeding and or stiching I have spent days trying to get baked lighting to look good. I use a simple low poly style. No matter what I do, I get this type of effect (blotchy shadows and odd dark lines) Here are my settings Baking a scene already takes around 4 hours, not sure I can increase the resolution any more without Unity crashing during the bake. Am I doing something wrong? Feel like Ive tried everything.
0
GameObject not destroyed in ExecuteInEditMode and spooky Instantiating I was trying to get familiar with Unity's ExecuteInEditMode Everything is fine it keeps the old object although I have deleted them. And one more thing, although every thing (cube) is instantiated is set as child of GameObject script is attached to, they where the other cubes come from? I have this code using System.Collections using System.Collections.Generic using UnityEngine ExecuteInEditMode public class Road MonoBehaviour public List lt Vector3 gt points new List lt Vector3 gt () public List lt GameObject gt gameObjects new List lt GameObject gt () private int count 0 void Start() void Update() if(count! points.Count) count points.Count foreach(GameObject g in gameObjects) DestroyImmediate(g) gameObjects.Clear() int i 0 foreach (Vector3 point in points) Debug.Log( i " " point) GameObject tem Instantiate(GameObject.CreatePrimitive(PrimitiveType.Cube), point, Quaternion.identity) tem.transform.parent gameObject.transform gameObjects.Add(tem) Here is a snap
0
Moving a platform left to right with continuous movement I made a 2D game with Unity, and I am trying to create a platform that will move from left to right continuously, but I don't know how to make the platform move a greater distance then 1 to 1 units because I use the Mathf.Sin function. I can only control the speed of the platform. Here is my code private Vector2 startPosition private int speed void Start () startPosition transform.position speed 3 void Update() transform.position new Vector2(startPosition.x Mathf.Sin(Time.time speed), transform.position.y) Here is what the code actually does How can I control the distance that the platform can move to each side? For now, it can only move 1 unit to each side.
0
Combine Unity games in one app I want to combine multiple Unity games in one Unity app (or other framework if necessary). This app would have a bunch of buttons that will start the desired game. Is this possible and what would be the best way to do this? Thanks!
0
Foreach list loop problem I am having a problem with a foreach loop. When my AOE ability hits an enemy it creates a CircleCollider2D and puts all the enemies on a list, which then the loop goes through and adds damage to their scripts. private void OnTriggerEnter2D(Collider2D other) if(other.tag "Enemy") targets.Add(other) foreach (Collider2D enemy in targets) EnemyHealth hp enemy.GetComponentInChildren lt EnemyHealth gt () hp.TakeDamage(abilityConfig.baseDamage) print(enemy.name " takes " abilityConfig.baseDamage "damage!") But as you can see from the picture below the loop goes 3 times over one enemy, 2 times over the second one and once over the third. As these enemies are the same type they all have the same EnemyHealth script. If anyone would point me in the right direction I would greatly appreciate it.
0
is there any method to simply ignore some files in unity build? as im trying to build my new app on unity android specially when i want to use gradle, there is always some conflict with manifest or libraries and ..... for debug and problem exploration i need to ignore some folders to check for those bugs instead of need to move them somewhere else. i just thought about git branching but it can cause lots of branches and maybe not efficient
0
A pathfinding for dynamic obstacles and player made blockages? Hi I'm creating a TD in Unity 5 and need some help with my Pathfinding. I'm going to use Arons A pathfinding for my AI which enables me to use dynamic objects and update the path during run time. However in my game I want the player to be able to block the minions with special turrets which will force the minions to attack the "block tower" instead to get past to their destination. How could I accomplish something like this? Image for more clarity
0
How to make changes to array of prefabs in editor to be visible in game window I attached the following script to an empty game object (EnemiesGO) in the editor. public class EnemiesScript System.Serializable public struct EnemyWithType public EnemyScript enemy public EnemyScript.Type enemyType public EnemyWithType enemyPrefabs public EnemyScript enemies void Start () enemies new EnemyScript enemyPrefabs.Length for (int i 0 i lt enemyPrefabs.Length i ) enemies i Instantiate lt EnemyScript gt (enemyPrefabs i .enemy) enemies i .enemyCategory enemyPrefabs i .enemyType When I was populating enemyPrefabs (through the editor) I didn't see the prefabs in the popup selection window so I dragged them directly from the Assets window Assets Resources Prefabs EnemyPrefabs. My question is two fold. If it is possible, how can I get the populated enemyPrefabs array to be displayed in the game window scene window before I run the game? In general, I would like to see changes effected from the editor in the game window before I run the game. How can I access the EnemyPrefabs folder from the popup selection window?
0
Stencil test doesn't work at all in Unity when I am using a custom shader I am using Unity 2019.3 and I have a custom shader A which contains the code Stencil Ref 5 Comp Equal Pass Keep And the other custom shader B contains the code Stencil Ref 5 Comp Always Pass Replace The stencil test can do the right thing only if I add Fallback "Diffuse" in B, otherwise, it's never working. And A has no code related to Fallback. Since shader A is using for post processing and I did something like buffer.SetGlobalTexture(ShaderID. MainTex,source) buffer.SetRenderTarget(destination) buffer.DrawMesh(mesh,Matrix4x4.identity,material,0,pass) The material uses shader A. Does this cause the issue because before today, I never use the Fallback during stencil test. PS. You can use this and scene named SSS as example. In that scene the shader named Unlit PBR has this issue. If you delete Fallback "Diffuse in that shader, the post processing effect never works.
0
How to make an object that has no rigidbody2d component smoothly fall on the ground in Unty2d? I have two character in my game enemy and main character. Enemy can throw different objects into the main character. For this moment i am doing this action in such way void FixedUpdate() if (CanMove) transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) public void StartMove(bool canMove) CanMove canMove TargetPlayer GameObject.FindGameObjectWithTag(Tag).transform rigidbody2D.gravityScale 0 This script is attached to the prefab of the object that will be thrown into main character by the enemy. This script is working, but in this case the object that was thrown will follow by main character all the time, because of this line of code transform.position Vector2.MoveTowards(transform.position, TargetPlayer.transform.position, 15 Time.deltaTime) To my mind this is not good, because i want to give my player the opportunity to escape from the object that was thrown at him. For example run away. When the object reaches the player position (and the player is on the new position) he will simply fall onto the ground. I did this, but this wasn't looking nice, because when the object was reaching his position, he was hanging in the air. Can anyone give me an advice how to make this process more good looking? Edit I need to make good looking movement of the object, that was thrown by the enemy into main character. Every frame i am moving the instantiated object to the current player position. So the player can't escape from that object, because he always knows current player position. I think that this is not good idea, and i want to give to player an opportunity to run away from that object. In this case i am saving the position of the player into variable, and then every frame i am moving the instantiated object to that position. So when the player run away, the object, that was thrown doesn't know anything about new position of my player. But this is looking not good, because when the object is reaches its destination position he hangs in the air(( Edit 2 I was thinking about destroying that object anyway, but to my mind this will not look good the object is moving and suddenly disappears from screen(. May there is some ways how to make him smoothly fall onto the ground? The problem is in that this instantiated object has no Rigidbody2d component attached to it, so it will never fall down by itself.
0
Would creating a player scriptable game using Unreal Engine or Unity violate their license agreement? I want to create a game in Unity or UE4 which allows the user to write scripts in Python and run them mainly to control the AI. I will have to find a way to enable runtime script execution first. After searching the internet i was able to find some ways that may work. What i cant find an answer for is how to limit the parts of engine and game code the user has access to so that the player doesnt feel like he's playing it in God mode. And the main question is that even if i am able to restrict access to the API will it violate the terms of agreement for these commercial engines because the player will get access to the underlying engine and will be manipulating objects within it. I don't intend to make a moddable game just a game that requires you to write some code but that would be an extreme case to think about.
0
Unity 4 Some Rigidbodies Won't Fall Asleep I'm having this problem in the free edition of Unity 4.1 where rigidbodies aren't falling asleep (and yes, I've tried playing with the sleepVelocity and sleepAngularVelocity values!). I've read the docs at http docs.unity3d.com Documentation Components RigidbodySleeping.html but cannot figure out the problem. Here is a screenshot demonstrating my problem Rigidbody Sleep Diagram http uberlethal.com random rigidbody sleeping.png I wrote a script that is attached to the rigidbodies in question, which sets the material color to red if the rigidbody is currently asleep or green if it is awake. The screenshot was taken when all objects were at rest. As you can see, not all of the gameobjects are sleeping. Each piece of debris you see on screen is its own gameobject with a rigidbody and collider. The Unity docs I linked to above state the following Rigidbodies automatically wake up when another rigidbody collides with the sleeping rigidbody when adding forces. Perhaps some clarification on the above might help solve this issue If two rigidbodies are touching when they fall to quot rest quot , will they never stay asleep? Put another way, would they just keep interrupting each other's sleep? As for the quot adding forces quot part, do sleeping rigidbodies awake only when forces are added directly to them, or when any force is added to any object (this is important because I am using a rigidbody character controller which moves via AddForce() calls) I have tried manually sleeping objects myself with undesired results. What usually happens when I do this is that some objects will remain suspended in the air. Let me know if you need other details I have tried a great deal of things.
0
Changing sprite tint over time in Unity. Sprites affected by "light" Recently I was playing "Altos Adventure" on mobile. I was curious how I could implement an effect similar to their game background. The sprites tint over time to match the time of a day. It's blue in the morning, orange in the evening. Sky color is changing and also mountains tint. I believe it is possible to change solid color sprite and it seems like mountains have only one color individually. Maybe they use other half transparent sprites to change the tint of the entire scene? Like half transparent curtain. But it doesn't explain the smooth transition between colors during the time. Any ideas how I can do the same with Unity and Photoshop? I am also interested in mountain fading effect which appears during rain or snowfall. See the background behaviour lighting effect in more detail in this video Screenshots with different tints of background
0
How to modularly call a script based on parameters within the script? I am coding an interaction system in Unity that does things based on whether the player taps interaction, or holds interaction. Each object holds their own scripts of how a player can interact with them and what happens (e.g., they can physically lift an object, add an object to their inventory, open close a door, etc) What I want is for the interactable object to call component scripts that have been added to it and categorized as tapInteraction or holdInteraction, but I also want the component scripts to be separated from how they're called (e.g., they might be called via tap or hold, it shouldn't matter). If I use interfaces, the tapInteraction could check for GetComponent lt ITap gt () and the holdInteraction could check for GetComponent lt IHold gt (), but then wouldn't each action need separate scripts defined as Lift ITap and Lift IHold? I feel like there would be a lot of repetition. I'm wondering if there is some better way to go about this. EDIT Thank you very much for the input DMGregory and Alex F! I ended up going with an interface approach similar to what Alex F answered, but with two key differences It was very important to me to have the actions as components on the gameobject since a specific action (e.g. Lift or AddToInventory) would have a large amount of customization from object to object. I also wanted the interaction to return a status as to whether it succeeded or not. As such I created a base class Interaction that implements the interface IInteraction with a bool TryInteraction method, and registers deregisters itself to an interactable object via OnEnable and OnDisable as the tapAction or holdAction depending on if that Interaction is set as a tapAction or holdAction. InteractionLift and InteractionInventoryPickUp inherit that base Interaction class, they implement the TryInteraction interface, and depending on their parameters will register themselves to a interactable object script as either the hold or tap action. Then the interactable object fires the hold or tap TryInteraction accordingly.
0
Draw line inwards in Unity using Line Renderer Is there a way to draw the line inwards instead of from the center using Line Renderer in Unity? Another option would be to move the Vector points inwards by half the width of the line, but If I have a complex polygon how do I do it uniformly? EDIT Found this https stackoverflow.com questions 1109536 an algorithm for inflating deflating offsetting buffering polygons which may be useful
0
How can I draw a specific GameObject into a texture in Unity? I need to draw only a few specific objects into a texture (with their material) and then use that RenderTexture as a texture for an another object. I think Graphics.DrawMesh() and Graphics.SetRenderTarget() would be helpful, but I'm not sure. Ultimately I'm trying to create refractive water, which will refract only specified GameObjects, not layers. How can I do this?
0
Calling Functions from Other Scripts Say I have three different gameObjevcts, each representing rock, paper or scissors. These objects all have a Player script attached to them. The Player script has two functions i want to use, MoveSelected(), MoveNotSeleccted(). When the function CPUMove() is called, I want the program to randomly choose one of the three moves. My question is, how do I call a either of the functions fro another script RPS Game? I thought of using Invoke() somehow but after trying couple of things with it, I got no where. Can someone please help me out? public class RPS Game public void CPUMove() int rand Random.Range(1, 3) if(rand 1) call MoveSelected() for one of the three Player objects and MoveNotSelected() for the other two else if(rand 2) call MoveSelected() for one of the three Player objects and MoveNotSelected() for the other two else if(rand 3) call MoveSelected() for one of the three Player objects and MoveNotSelected() for the other two
0
Constraining an orthographic camera to an isometric world I am using Unity3D, and I am building an isometric world by rotating a plane on the Y axis by 4.205 units. I am using an orthographic camera. I want to constrain the camera so that the viewport never shows the area outside of the world (in green). How can I calculate the corner points of my rotated plane in screen coordinates, represented by green? How do I stop the camera from scrolling to prevent it from showing the area outside the world, represented by gray?
0
How to align the Polygon Collider 2D in Unity to match the position of Sprite? How to align the Polygon Collider 2D in Unity to match the position of Sprite? I have a game object. It has a Sprite Renderer with an image. Now I add a Polygon Collider 2D component to the game object, that generates a collider. The shape of the generated collider is correct as expected i.e. it matches the image from the Sprite Renderer. But the position of the collider is wrong. Here you can see what I mean For sure I have a solution I can manually configure the Offset of the Polygon Collider 2D. But that would take a significant amount of efforts and time (because I have a lot of such game objects, which need to have a sprite and collider). So, I am hoping to find a solution which would position the generated collider correctly. I.e. in such a way, so that the boundaries of the collider would match the boundaries of the sprite.
0
How do I link a GameObject activated state to a UI button being held? How do I go about this functionality When a user taps and still holds onto a UI button, a GameObject will be set active, when they release the UI button, the GameObject will be deactivated.
0
Material colours in unity not displaying correctly? Even though I've picked blue the color is displayed as something pinkish. All colors are like this
0
In Unity displaying long lists of information to screen? Tables? Hello folks I'm making a little game for fun in unity, Its a boxing management sim. I've got the code done to create boxers and give them many properties such as names, weights, stats, etc. I've made another screen , lets call it 'office screen' for now. In that I want to open a panel which will show all the boxers in the game (ideally I'd like to be able to make the player be able to filter these results by which company he's signed to etc but I think that might be out of my skill range so maybe i will just make a separate screen for Owned Boxers) But I cannot seem to find a way to display all these infos in a table with columns such as Name Age Company etc I have had a go just using the UI Text components and panels. But thing is, there will be approx 100 boxers or more and this number will always change also. Any ideas for this in Unity specifically? EDIT I am storing all the data just as variables (i think fields) in a class called Boxer which is assigned as a component of a new GameObject i instantiate at the time each boxer is created. So each boxer has its own gameobject. EDIT 2 D i've found this https docs.microsoft.com en us aspnet mvc overview older versions 1 models data displaying a table of database data cs would this be the sort of thing I can add to Unity (assuming I can follow along with the guide)? Thanks for any help
0
snap an object to another object? so I have some walls which are cubes stretched along a direction.and I have some windows and doors that are suppose to snap to a wall and don't let go until the desired location is out of the snapping range.and in the meantime I want the Objects to move along the wall but never detach from it. if I wasn't clear enough let me know.
0
Draw wireframe models for Gear VR app in Unity I want to create a 3D Android app for Gear VR that does lets me do the following Read an input file with a bunch of coordinates of points (including information about how they should be connected) Draw a wireframe model with these points Walk around and through the model in first person to look at it from different angles using a gamepad controller. I don't want to directly interact with it! (Maybe have more than one model displayed at the same time, including filled ones) Is it possible to draw 3D wireframe models in Unity using coordinates instead of using already finished models that were created in Blender Maya etc, and if so, how?
0
Unity ceiling light issues I'm trying to get back into Unity and I've been playing around with lighting. I modelled a simple lightbulb in Maya and have been trying to create a hanging ceiling light but I'm struggling to get it to work. No matter where I place the point light, it appears to originate from the ceiling and the bulb remains dark. Ideally, I would like the light to originate from inside the bulb and spread across most of the room, while also making the bulb glow. I'm sure this is a simple task but I would really appreciate any tips in the right direction. Thanks
0
Implementing a 4x4 Game Board I struggle with efficiency in code, and I want to start my game off on the right foot. I have a game that I'm making a 4 x 4 map of 'tiles' that a user can build their 'town' on. To keep track of the tiles, I'm planning on simply having a size 16 array of the type of my 'mapTile' enum. EX enum MapTiles defaultTile, homeBase, farm1, farm2 ...and so on... static MapTiles playerMap MapTiles 16 ... default map setup ... Is there a way that is more efficient or more easy to extend way to implement such a map? I'm using Unity and C mostly, though i'm willing to work with any Unity capable language if you have a clever answer.
0
Different Screen Sizes and Camera in Unity Now I know that no matter what the screen size is the camera will keep its height, so no worries about that. My question is, is there a way to manipulate the camera, either its orthographic size, or its viewport rect width, height, x or y so that the camera will fit perfectly on different screen resolutions. I know this a perfect solution for supporting different screens problem but how do other games do that? I mean I took some games from google play like bunny skater, or stick hero, those games look the same on Huawei P6 which has 1280x720 resoltuion, on Prestigio Multipad 4 which has 1024x768 and on HP Slate 7 which has 1024 x 600 resultion, now my question is how do they do that? I think the closest solution to this is to manipulate viewport rect of the camera, I'm saying this because I found a script that does so but it leaves black bars on top and bottom, the game looks the same on every device though but as I said it leaves black bars on top and bottom, so is there a solution on how to do this?
0
Scene building for procedurally generated tile based world in Unity i'm making a procedurally generated side scrolling and destructible tile based world. So far I've got the values generator (for deciding which tile to place where) a testing scene generating one object per tile (a mesh with 2d box collider, inactive at start) map chunking (separating the map into chunks to show only what is visible) visibility based on orthographic camera size (it's not much but the camera can zoom in or out) the chunks are 32x32 tiles in size the maximum chunks I've seen is around 25 This works fine for testing the world generation, however there is massive stuttering when moving around with camera zoomed out to the maximum. It's less when zoomed in, but it is still noticeable. From testing, I've found out that its obviously the building in the scene that causes the major part of the stuttering. I've been searching for better ways of building the scene but there are a few constraints that make most of the non viable The world is destroyable, so I need to be able to interact with each tile There are textures coming on top of the tile texture depending on context (selection rectangle, decoration, glow...) The tile texture itself is not a single sprite but a repeatable texture, so it needs to be places based on coordinates so it properly repeats itself. So far I've looked at TileMaps Mesh melding Texture bombing None of these seem to be able to fulfill the constraints fully. Is there a way to fulfill the constraints while improving scene building or am I missing something? Please help.
0
Additive Scene Loading Buttons not Becoming 'Active' I'm quite new to Unity but I'm making a game, and have created a simple Pause menu, when a key is pressed (escape), I just load a Pause scene, additively, and set that Pause scene to the active scene, however, only the buttons on the previous 'game' scene are interactive. The mouseEnter, exit etc aren't triggering on the pause menu buttons, despite the pause menu being overlayed on top of the 'game' scene the Pause scene being the active one and the 'game' scene buttons are still the interactive ones (i.e. register clicks, mouse overs etc). Obviously when I open the pause menu, I want the pause menu buttons to be the interactive ones (registering clicks, mouse over etc), not the previous 'game' scene buttons. The pause menu scene interacts perfectly when loaded additively with a scene that had no buttons. Many thanks.
0
Why use convex polygons and not concave ones in path finding? I read in Unity's path finding documentation that they use convex polygons because there won't be any 'obstruction' between 2 points. Then they add their vertices as nodes along with starting and ending points and traverse them using A algorithm to reach the required destination. However, I do not understand what they mean by quot no obstruction between 2 points quot . I tried to check the differences between concave and convex polygons but only the angle differences come up (in convex the interior angles must be less than 180 degrees)
0
Facilitator UI on desktop screen for VR Hey and thanks in advance for any help pointers The solution is probably straight forward but i am still a little inexperienced (while creating quite a few different VR unity projects mostly study related, i never really build anything so the editor allowed for some shortcuts. see below). I am currently developing for Windows mixed reality with unity. I am struggling to figure out how to make a (possibly secondary) application window run on the desktop that can be used during facilitated VR experiences to change settings and generally provide facilitator input to the application while the participant would just perceive the VR world. Edit I have a similar project that is developed with Steam vr library Open VR that works exactly as expected and portrayed by the unity editor i.e. the desktop will shows the ingame footage the screenspace overlay UI (which is interactable).Nevertheless quite a few features where implemented with the MixedRealityToolkit so I'd prefer to stick with that. And was wondering if there is a way to achieve the same similar behavior with it. Now with MRTK everything works straight forward when running from unity editor just making a canvas screenspace will prevent it from showing in vr while it can still be interacted with. the problem is that the facilitators themselves are a third party and having a build would just make their handling of the solution much easier. Not to mention performance gains from building and cleaning the project(?). it will probably come down to creating a secondary window that runs on the desktop since my understanding is that uwp with MRTK just runs in the wmr portal rather than a separate app and that the WMR portal simply copies the Headset render to the desktop. But i am completely blank on how to achieve this and was hoping that someone might have struggled with this before. But i couldn't really find anything. I'd prefer not to have to resolve to Networking, and will attempt to convert to Steam VR OpenVR in the meantime..
0
Make an arrow to point at a direction from UI I want to have a guiding arrow on the left side of UI. The arrow is child of the player's camera and it's rendered from another camera into render texture. The render texture is displayed on the screen. The arrow is rotated via transform.LookAt(targetPosition) The problem I'm having is that although it does point in the right direction, form player's point of view it looks like the arrow is pointing somewhere else. I want that arrow to point from the point where it's placed on the UI. It should look something like this I tried to do this Vector3 direction targetPosition arrowRawImage.rectTransform.position transform.LookAt(direction) but it didn't work.
0
Multiplayer turn based Android iOS We're developing a mobile endless runner game, on Unity3d where you can challenge your Facebook friends. The only interaction between the players is the challenge one player challenges the other, then each player plays when he wants, and after both players finish (when their character dies), their scores are compared to determine the winner. What system would you recommend that would allow us to implement this functionality, considering scalability, cost and ease of use? Thanks in advance!
0
My Canvas has an image which I am using for my background but it is blocking my Camera from seeing my Game Scene So I am not entirely sure how to explain this as I have not had any luck searching online and I'm sure this is a simple problem but I'm being stupid and can't see it. I have a Canvas which is for my UI obviously and I have added an Image as a Background to the Canvas. The problem I am having is that due to the Image on the Canvas it is blocking my Camera from seeing the Scene with my game object you can see in the background. On the Canvas, I have tried playing around with Sort Order, Render Mode, and see if I could edit the Z Position but I can't seem to do that. I'm not too sure what I have missed but I must have missed something. Any assistance would be great.
0
Make a light only affect one object I'm wondering if it's possible to make a light source only affect one object? I know that it's possible to use layers and culling mask, but then I would need one layer for every single object which is not possible. Is there a way for example that I could make only children or siblings be affected by a light source? Or other solution? Have a nice day! Update 1
0
Play a sound on button click before loading the load scene in Unity3D I am trying to play the sound of the button click before loading the scene in unity. However, the sound is never played. Below is my code, help would be appreciated. public void RestartGame() audioManager.PlaySound(forwardSound) StartCoroutine(DelaySceneLoad("Gameplay")) IEnumerator DelaySceneLoad(string scene) yield return new WaitForSeconds(forwardSound.length) GameTracker.SetGameOver(false) SceneManager.LoadScene(scene)
0
How can I add up the Transform GameObjects in the Array of Waypoints in Unity? I come up with this code and I try to get the waypoint 1 when I reach the waypoint and it adds up till the last waypoint. I get Array is out of Index error. I guess I need and foreach loop of waypoints ? Code public float speed public float turnSpeed public Transform waypoints private int currentWp 0 void FixedUpdate () if(waypoints.Length gt currentWp) return player.position Vector3.MoveTowards(player.position, waypoints currentWp .transform.position, speed Time.deltaTime) var rotation Quaternion.LookRotation(waypoints currentWp .transform.position player.position) player.rotation Quaternion.Slerp (player.rotation, rotation, turnSpeed Time.deltaTime) float distance Vector3.Distance(player.position, waypoints currentWp .position) if(distance lt 10) currentWp
0
How does Unity Static batch handle submeshes I have the following 2 meshes Mesh 1 Submesh 1 Mat 1 Submesh 2 Mat 2 Mesh 2 Submesh 3 Mat 1 (same as mat1 from submesh 1) Since submesh 1 and 3 have the same material and they are all static, I'd like to render submesh 1 and 3 in a single drawcall. However, Unity is failing to batch those submeshes together. Is there a way to achieve this?