#archived-code-general
1 messages ยท Page 44 of 1
stop using an instance material - that is not the asset you want to change. Change the actual asset you want to change.
like dude think me of an artist i am playing the game and material is instance (dont tell me dont use instance, think of as this is the situation). while i am playing i want to change the material then i change of its color. when i stopped playing i dont want to copy material then find the actual material and paste it. i want to save the changes when i exit of play mode
Are you trying to let players of the game permanently modify materials in the build?
You cannot modify assets that are part of the build
imagine 20 prefabs use that material now i have to reference each of them
thats why i want to merge / override that asset
without losing the reference
~~The sneaky way you could try is
https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html
and
https://docs.unity3d.com/ScriptReference/JsonUtility.FromJsonOverwrite.html~~
serialize the material to json, and deserialize into the original
oh actually
YOu'd use this https://docs.unity3d.com/ScriptReference/EditorJsonUtility.FromJsonOverwrite.html and ToJson
thanks ill try it as soon as im available
Hi all!
Iโm creating a class to divide my terrain into a grid and store information about each cell. I have created a scriptable object to save this data in and I am trying save it to the instance of the class it is from by setting a variable in the class to it. But when I press stop the variable resets.
The idea is that the first time it runs it will generate a grid and save it to the scriptable object but the second time I want it to know it already has the object and load it from memory. What is the best way to do this?
I've considered checking the file path but I would much rather it was just stored with the class. Is this possible?
what does this mean?
Is this a Roblox thing?
or are we talking about networking?
Depending on what your actual use case is you want either a Transform or a Matrix4x4
Without further context, you most likely are thinking of Transform
but Unity doesn't work like Roblox
Transforms are full-fledged components attached to GameObjects
they are not just "properties"
what is a "workspace"?
ok well
that's not a thing in Unity
maybe "Scene"?
but scenes cannot directly have "values"
they only contain GameObjects
If you just want a basic general purpose data type that can just contain position/rotation data you could use Matrix4x4 or make your own struct
Matrix4x4 also contains scale information (as does Transform)
wdym by this
You are wrong
i tried like this just to be sure but it doesnt work, where i am mistaken
GameObjects are "just identities". Transforms are components on GameObjects which contain position/rotation/scale and parent/child relationship data.
you never called AssetDatabase.Save
??
Transforms are "actual components in the world"
still does not work
on actual GameObjects, in the game world
The only things that are "visible" in Unity are Renderers
Unity breaks its objects down into various components
the visible components are Renderers
They don't know what they're saying. They don't do Unity nor C#.
We just had an argument in #๐ปโcode-beginner about how their python code was better than someone's C# version of it
they render things
Pretty much the same thing you said in the other channel
"is it visible" is a bad definition of "does it exist". Physics bodies in Unity are also not directly visible. Nonetheless they interact with each other and are physically simulated just the same.
Nothing of this is related to logic or syntax
they exist in the world
the world is and always has been imaginary
it's a video game
i added this to after i overwrite it but still nothing changes
yes
Every GameObject has a Transform
every Transform is attached to a GameObject (as all Components are)
Transform is special in that it is the only Component every GameObject has
the Transform defines the center point of the GameObject
you saw it incorrectly
there is no other "center" to base from
Every other component uses the Transform position as the position/pivot of the GameObject
Aren't you brand new to Unity anyway? How long could "always" have been?
A couple days?
Hi again, I asked about this earlier and ended up finding out that I can't get scriptable objects to save during a pre build process, the code below seems to work fine when called on a normal monobehaviour however not during preprocessing. My guess is that the result of SetDirty does not get called during the build steps. Is there a better way to save these values? Will using serialised properties work? Or is there a specific way I should be interacting with SO with for saving during the build phase?
public class BuildVersion : IPreprocessBuildWithReport
{
public int callbackOrder => 0;
public void OnPreprocessBuild(BuildReport report)
{
int version = PlayerSettings.Android.bundleVersionCode;
BuildInformationSO buildInformation = Resources.Load<BuildInformationSO>("[1][ Object Data ]/[ Scriptable Objects ]/[ Build Information Asset ]");
buildInformation.SetAndroidBuildVersionCode(version);
EditorUtility.SetDirty(buildInformation);
Debug.Log($" <color=#00AA99>ยงยป</color> Build Version: {version}");
}
}```
<@&502884371011731486> (nitro scammer)
my player starts to glitch when i try to run this script to keep it within the bounds of the maze. what could be the reason? is it the clamp function?
is your player using a Rigidbody to move?
yes
well there's your problem
how do i rectify it
you're teleporting your player with this script
which does not play well with Rigidbody motion
oh i see
if you want to limit the area a Rigidbody can move in, you should use colliders as boundaries
how do i do that
how do you do what?
use colliders as boundaries?
You place objects with colliders in the world
i dont get what you mean
What part are you confused about exactly?
i have one script for player movement for the player to move left, right, up and down and the other script is for boundaires
how i can prevent the glitch on the screen
ok and I'm saying instead of doing that
you would place objects in the world with colliders
to prevent your player from moving past them
this is how it is
okay. do you know how to do that
okay. what will this game object be ?
2D game object?
Wdym? It will be an object that has a collider that acts as a boundary
there's not such thing as a "2d game object"
there are only GameObjects
2D box collider?
oh
is there nothing i can do to the code?
you can do all kinds of things to the code
If you want real boundaries for your Rigidbodies you need colliders
presumably if this is meant to be the screen boundaries you'll eventually want to write code that positions the colliders properly to fit the screen.
Hi everyone, sorry to bump this. Just wondering if anyone could help solve this before I head off from work tonight. To explain the problem again, I'm a bit stuck with getting data to save from a build pre-processing event, that I can then use during runtime of the built game. Any help would be apreciated.
Hi, I have a RectTransform that keeps it's position, even though the screen dimension change. How could I make it so that position adapts to the display format, thanks!
Change its anchoring preset from the Rect Transform's Inspector
I think I set it's pivot already, that should be it?
Yeah okay, I was just looking at the wrong thing..
rect wont change but position does
so yeah should be the right thing, just need to make it work somehow
cause right now it doesnt
at least position changes a bit
Also log the .anchoredPosition.
yo i have this script that rotates an object from a joystick axis and i was wondering if there's a simple way to smoothen out the rotation, because atm it just sets the transform.right to the input vector which is very sudden
Seems to stay the same, that's what we were hoping for?
Yeah it's the position of the object relative to its anchoring preset
GetAxisRaw has zero smoothing. You can use GetAxis (and configure the smoothing values in the input manager settings), or apply your own layer of smoothing
Show how said preset is done from the Inspector
oh right! i completely forgot about that attribute, thank you sm!
Middle-Center
It won't stretch to fill its container
Click that square and stretch both axes
Hmm reading your question again, you might want to use the current method, but use for example oh it's 2D, maybe just store the angle and use Vector3.Slerp to smooth the dir variableMathf.LerpAngle/MoveTowardsAngle or something
Probably works better for what you want
I'm using this RectTransform to align 3D objects, do you think once stretched, if I line it up properly, I should get consistent results across different displays?
Probably yes. Stretching makes the position and size relative to the borders of the container (if there's no container, it's your Canvas).
You will be able to add some margins if you want, once stretched these will change to say Top/Bottom/Left/Right
Okay, I will play around with that then, so I should probably align it in inspector first and then use margins if needed?
You can use Ctrl or Alt, to also set the object's position while you change the anchoring. The keybinds will be displayed when you click that square
Yeah, I guess you meant Shift, will have some experimenting to do then!
Also see https://docs.unity3d.com/Packages/com.unity.ugui@latest/index.html?subfolder=/manual/UIBasicLayout.html, good reference for starters
@simple egret Yeah, after testing a bit, it doesn't seem like with using RectTransform will work for a 3D object, I think calculating a position using the screen dimensions will probably make more sense, still not a 100% sure though.
But the object always moves out of position, it never keeps the same relative on screen position.
How do I make it so that Unity can ask the user for permissions to their microphone? For my game I need to use DictationRecognizer.
Not sure what you mean here, Rect Transform is only available for canvases. Surely the canvas can be in world-space, but positioning it with the RectTransform's anchoredPosition as you should always do, it will work
If you need sizes or positions to adapt depending on the number of objects, then take a look at content size fitters, and layout groups.
This should really go in #๐ฒโui-ux though
Also if you Instantiate the object make sure you use the overload that takes in a parent Transform. Avoid setting the parent afterwards, because it will change the position to adapt it to the parent
I know you can set up default references to prefabs for scripts in the unity editor, but is there a way to use those values with addcomponent at runtime?
add a component with references already set up?
sounds really basic, but is there a simple way to change a prefab's textmeshpro in the editor?
I have a prefab from an existing project I want to reuse, but I just want to change the text inside it.
clicking on it, does not really do anything.
well, if that would not work, then the only other way was to attach a script and edit it via a script, so I thought it might be useful
so it is now selected,
Just open the prefab by double-clicking it, it will appear in the Scene View
Select the object with the Text on it, and change its properties in the Inspector
@simple egret
Thanks,
I tested with new prefab it works,
seems like the old used something other than textmeshpro
i have split my complex objects into a bunch (40) smaller, convex parts and put 40 meshcolliders onto the object.
but it doesnt work, object has no collision. any idea why?
what does "object has no collision" mean? What is the nature of the collision you are expecting?
well phsyics collision with another collider. bouncing off stuff
does your object have a Rigidbody
Where is the Rigidbody?
on the parent
You need a Rigidbody to get physical interactions
I need to build a visual studio class library to unity to export a nuget package without using 3rd party resources. How would I do this?
i got everything i need, i have a RB, convex colliders etc. but let me double check
haha alright, found the issue. my collider mesh gets scaled 10 times bigger or something and i had gizmos disabled, so didnt notice
Yes colliders are subject to Transform scaling
correction: for whatever reason the renderers transform is at 0.11 scale after import
Renderers are also subject to Transform scaling ๐
I've got a dice rolling game. In my game, I want 3d rendered dice to roll in the 2d UI, so what I'm doing is parenting a camera object to a dice object and then sending the output of that camera to a Render Texture that's on my UI. This works perfectly for 1 die - but if I want to track any number of die, each with their own camera, when I create a prefab, each instance of that prefab has that same initial Render Texture, so each display on the UI is the same die, I assume because whichever camera instance writes to the render texture last each frame is the one that 'sticks'. Is there a way I can have any number of cameras projecting onto different textures at runtime?
How do people deal with pooled objects in terms of releasing back to the pool? Do you make them aware that they are pooled?
I once solved this by letting the user write Game.Instantiate()/Destroy which checked with some static if it's part of any pool and use appropriate create/release method. But this kind of approach requires everyone on the project to follow that pattern.
I like the idea of the genericness that you could add a Pool into the scene to reference a prefab and it will handle it behind the scene, but then again you would need to support pooled logic, e.g. use OnEnable/OnDisable for startup/cleanup so you already create some "dependency" between allowing pooling.
I think running multiple cameras is very expensive, so if it's scaling with a lot of die you might reconsider your approach.
10 should be fine. it's a single player turn-based RPG.
You should be able to create the RT in runtime and just link them?
yeah that works. didn't realize i could roll a new RT in real time.
im getting issues with my build that arent showing up in the editor playtest, how could i mitigate these? and why might they happen? for example, my players arm rotates slightly wrong compared to the actual build?
Did you try running developer build & look at logs & attach debugger?
ill give it a go but
i dont see how that would help, its not actually an error
You never know util you check ๐
do you see what im talking about here?
when the thing does right above or below tthe player it flashes up briefly
Possibly something to do with framerate.
You've only experienced slow frame rate in the editor, and when you run the build you have higher framerate which causes your update loop run more then your fixed update for example.
i mean its going quite fast
That's one potential issue. You can start do logs in different part of your code and then build and try to pinpoint where it fails.
I cannot solve this kind of issue with not seeing code. But I think you can try some debugging steps first^^
if anyone knows anything about shaders, help in #archived-shaders would be appreciated
here is the code for the rotation of the arm
Please look on how you should post code here ๐
soz one moment
Does this flip the whole character as well or another script?
flipping the character is another script. i did a test where i did a build with update instead of fixedupdate, it seemed to fix it kinda? but it meant the player arm moves in the pause menu
it will still do it sometimes tho
if i dont flip the player arm as well as tthe player it will aim backwards
Guys, i have a assetbundle, i can see the .shader file into it, how i can make the game load it as shader with c# from that assetbundle?
Sorry don't have much time, but try swap order of setting rotation and localScale. If that doesn't work log the angle when just moving the arm where it flips with bug.
okay, thank you for your help!
will try this later
/// <summary>
/// Loads SpaceShuttle bundle in resources as Prefab Object
/// </summary>
internal static GameObject SpaceShuttle
{
get
{
if (_SpaceShuttle == null)
{
_SpaceShuttle = Bundles.SpaceShuttle.LoadAsset_Internal("assets/Game/SpaceShuttle/SpaceShuttle.prefab").Cast<GameObject>();
_SpaceShuttle.hideFlags |= HideFlags.DontUnloadUnusedAsset;
return _SpaceShuttle;
}
return _SpaceShuttle;
}
}
the same bundle has a shader that i want to load as resource
is called Booster.shader
but i dont know how to load as a shader asset like that.
what do you use to paste code out like that?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
im still looking but i can't find the answer of what i need :C
how i can load the shader from a assetbundle with script?
im trying to load
a .shader in the assetbundle
as a shader
so i can make a material out of it with script
have you googled it? because the first result when I do is how to load a shader from an asset bundle
This is a bad idea, right? https://hatebin.com/nrqlusfodp
yes
you're subscribing to events every frame. when the event is invoked each separate time you subscribed to the event will invoke that method
Let's say I have a rock I am trying to push off a cliff to the ground. I don't want the player to be able to move cause it's an endless runner until the rock hits the ground. If I subscribe in the awake function of the player script instead of the update one, it won't work when I spawn more PushableWall object in gametime. Here is the pushable wall script https://hatebin.com/tadsjqkiyv
your event doesn't appear to rely on specific instances or anything like that so you could make it static, then you only need to subscribe to it one time total. either that or every time a new wall is spawned you subscribe to the event on that object
Wait, it worked? thanks, could you explain why it work?
I'm trying to have a meteor explode into several chunks when destroyed. The chunks can have one of multiple possible textures, which will be assigned randomly. My idea was to use the particle system for this, by manually emitting one particle, then changing the material and repeating a certain amount of times, but changing the material for one chunk changes it for all of them. Is trying to use the particle system the right idea for this? (Unity 2D).
does anybody have any idea as to why the "events" drop down menu isn't appearing on my Player Input component? I've included screenshots, the one using "XRI..." in the actions field doesn't show any option for the event drop down. The other screenshot is of another project I have made that has the events drop down menu present.
nevermind I am a colossal fool. I just forgot to change the behavior settings
I have a 3 dimension dice which I roll in my game. How can I determine which side is up? My first thought is to loop through all the submeshes and determine the one that has the highest total y position, but is there a better way?
I would like to ask how do I program for an item to appear once I picked something up, specifically I have the outline of said item and want the item to appear within the outline once I pick it up
I assume this is more than 6 sizes so you can't just use your rotation to check the up direction easily
yeah N-sided
What I would do is make your dice prefab have N children, with each transform on one of the sides. Then check which transform is the highest.
This requires you to have a prefab for each dice with those children though
Has anyone ever made a rhythm game with or without wwise ? I have some questions about how to implement certain stuff
i cant get the object to move towards where the mouse was pressed
if (Input.GetButtonDown("Fire1") && inventory.myStuff.bullets > 0)
{
Vector3 shootDirection;
shootDirection = Input.mousePosition;
shootDirection.y = 0.0f;
shootDirection = Camera.main.ScreenToWorldPoint(shootDirection);
shootDirection = shootDirection - transform.position;
Rigidbody bulletInstance = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation) as Rigidbody;
bulletInstance.velocity = new Vector2(shootDirection.x * bulletSpeed, shootDirection.z * bulletSpeed);
inventory.myStuff.bullets--;
}
I don't suppose you know much about Blender? I'd be nice to be able to generate those transform positions from the center of the face there... unfortunately it looks like my "bounds" method only reports in local space so i'd have to do rotational math or something to figure out where they were in world space...
What you can do is add a child empty to the dice (or select a single vertex and separate it from mesh) for each side on the dice with the name of the empty equal to the dice side number then export that mesh. Then have a script that executes in edit mode that grabs all the children in the mesh and stores them in a list that can be used to check what side is currently face up
not totally sure I follow - do you mean export each face individually from blender?
No. Make the mesh a single object with multiple empty children to represent each side value
I understand that concept of placing empty transforms to represent the faces and then checking which one is the upmost, but i'm missing how to position those automatically?
use the cursor after setting it to the face. objects are always instantiated at the cursor in blender
that way it is consistently in the center of the face
ah an empty child in Blender ๐
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Ok. I added some axes in Blender and they're showing up in Unity as... children of the prefab I guess? I'm not able to grab them using getcomponentsinchildren. Not sure how I access those other children. I assume they're children of the MeshFilter?
if you drag the main object into the scene, it should be a gameobject with them as children
oy, thank you ๐
Thank you
You know how there's the void, "OnCollisionEnter"? Is there a way i can make something similar for myself? I'd like to be able to set something up that's called whenever a collider is being clicked on (I know there's something for this, I was just hoping to make it more custom)
in the jobs menu there's debugging depth options, you'l lwant to enable stack trace
i am emulating wwise and doing a specific thing with audio
i want my audio source 1 (yellow) to set its volume the same as the curve in the image, with it staying at 1 until my value hits 0.2, at which i want to fade it from volume 1 to volume 0 at value 0.437.
how can i do something like this?
it doesnt need to be curved btw, just a straight volume down works
Can I have an interface that requires the implementer to use other interfaces? I could do inheritance but inheritance is how I got here in the first place
TL;DR
i just wanna know how i can turn
0.2 - 0.437
into
1 - 0
a remapping function
remap, the name was on the tip of my tongue
im trying to split apart my code to component-ize it with default implementations but some parts depend on others in different interfaces
This?
I don't know either
that's. odd
Nobody found the solution either lol
i love when unity works
Its also not on preferences>jobs
do you have jobs the package installed in your package manager?
Yes, Jobs & Burst
hmm
do you have Unity.Collections installed?
No, I'll give it a go.
ooyh good one i forgot about collections
that one has nativearrays which is where a lot of leaks come from
Installing the package gave me
Library\PackageCache\com.unity.collections@1.2.4\Unity.Collections\NativeMultiHashMap.cs(84,60): error CS1503: Argument 1: cannot convert from 'U' to 'Unity.Collections.AllocatorManager.AllocatorHandle'
Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'```
stupid question but did you install all these packages from package manager, and what versions do you have for each?
collections 1.2.4 is pretty old IIRC ๐ค
(and what Unity version are you on?)
Yes, strictly from package manager only, and they're all updated. I'll send a ss
what version of Unity?
2022.2.7f1
looks like 2.1 is there, as a preview
Well you're kind of already in "preview" by using 2022 ๐
How can I run the unity codemod if I dismissed it when the modal first popped up?
For automatic API updating.
Got it all working, thanks @wide burrow
error CS0006: Metadata file 'Library/PackageCache/com.unity.ext.nunit@2.0.3/net35/unity-custom/nunit.framework.dll' could not be found
With all dependencies installed too
Haha, I'll just not debug my jobs
Ah, got it. I can trigger a recompile and it will run again.
I'm a little bit bothered by how similar the rotation factors seem to be however - I use AddRelativeTorque() with 3 random values each times a Random.value - is there a better way to get a good "roll"?
pick a random axis with Random.insideUnitSphere.normalized, then create a rotation from it with Quaternion.AngleAxis - and you can finally convert that quaternion to euler angles (for AddTorque) with .eulerAngles on it
I think this would give you a more uniform random rotation than picking from a "cube" of euler angles
I'll give it a shot. Ideally what I want to get is a "processing axis" - essentially a little bit of wobble, where the die is rotating in multiple axes at once.
(fwiw I'm sure AngleAxis accepts an axis of any length)
I think you'd need to continually add torque to get this kind of effect but not sure
Its the only way I can use Entities 1.0 though :(
I think I'd need to triple parent it like a gimbal; but nonetheless Random.insideUnitSphere worked really pretty well.
Hey I have changed my external editor to RIDER but every time I open project it opens scripts with VS
It does not save that I have chosen RIDER
how to make rider default?
try restarting unity
regenerated project files after you switched ?
Yes
I have the following static class for cross scene info sharing:
public static class Data
{
public static bool[] s_StarArray { get; set; }
}
My problem is that a player may play the game number 1 instead of playing the game number 0 first so the code that is going to change the bool array is like s_StarArray[1] = true.
How'd you guys face that issue?
I'm not sure it's clear exactly what the issue is. For whatever reason your player is entering game number 1, why does the value at [0] matter?
Is this a problem better served by using a dictionary?
You are trying to base the data on your player, which is a bad decision. Your array should know upfront, what games are available and those games should have an initial state which you then update locally with your player.
is there a way to turn airdrop with ios app on (10 minutes)
what is the Unity or Code relation here?
In iOS, sure
is there a separate thread for Netcode for GameObjects?
and howโฆ..?
Not really a Unity question
ok sorry
whole different discord pinned
That wasn't directed at you
thank you
lol im idiot
No you need iOS Swift or Objective C code
there is no iOS specific code in c#
Rotation of connected object.
what is the best way to move a car along road with navmesh, how to control it at corners
when it needs to turn
Hi everyone, I messaged last night but didn't get a reply. I wanted to know what the best way to save data that can be accessed on the build during a build preprocess, I have tried this with a ScriptableObject but it doesnt seem to save the data when setting it to Dirty. Any help would be apreceated
Hi, I'm looking for a way to add a gameobject during a build process only for debug builds, not release builds. This gameobject has a component which adds a lot of code to the build we don't want in our release builds. Outside of editing the .unity scene text file, is there a way to do this?
you can use json or binary format for complex and sensibile data,or for more easy you can use playerprefs
You can have some code in the scene that adds it but is blocked using compile defines, for example
#if UNITY_EDITOR
// this will only run in the editor
#endif
There may be a define for debug builds too, if not then you can add a custom define that you set for debug builds in the Player settings.
I may just look into writing a JSON then, PlayerPrefs unfortnatly don't carry over the saved data to the build, but a file written to resrources might
Issue is we're using external library where I can't edit the code. Can't create it during runtime either because it needs to be in the scene file. Thanks anyway.
It's super annoying 
Ah damn, yeah that is anoying. Sorry someone else may have a better idea at doing this then I do. Sorry
you can't edit any code?
Because it's an external library. So I can't add defines.
it doesn't need to be in the external code
Right, but this component needs to be in the scene from startup
why?
because unfortunately it doesn't work unless it is
I know its a bit of an odd aproach, but you could load the game up into a setup scene, and then additivly load the new scene
it would be strange to me if that were true and something like an initialise on load script wouldn't be sufficient
That way the object you need is already in the scene as you can create it before loading the new one.
scenes don't do anything particularly special here though, if you're additively loading a scene on startup you might as well just put it in a prefab and instantiate it - I feel like the idea it must be in a scene at editor time is an incorrect assumption?
How do people deal with pooled objects in terms of releasing back to the pool? Do you make them aware that they are pooled?
I once solved this by letting the user write Game.Instantiate()/Destroy which checked with some static if it's part of any pool and use appropriate create/release method. But this kind of approach requires everyone on the project to follow that pattern.
I like the idea of the genericness that you could add a Pool into the scene to reference a prefab and it will handle it behind the scene, but then again you would need to support pooled logic, e.g. use OnEnable/OnDisable for startup/cleanup so you already create some "dependency" between allowing pooling.
why when i destroy an object, the child count doesn't show the correct amount?
the debug.log shows the wrong amount
but it goes down everytime
so i had to change some code to stop deleting when the spell queue has 1 spell left instead of 0
which seems odd that its doing that lol
Objects are destroyed at the end of the frame
unparent the object before destroying it
@wintry crescent I ended up getting the 2d array setup for my tile grid. Thanks for the point in the right direction: ``` void SetTileData()
{
tileData = new TileData[baseTileMap.size.x, baseTileMap.size.y];
for (int x = baseTileMap.size.x, i = 0; i < (baseTileMap.size.x); x++, i++)
{
for (int y = baseTileMap.size.y, j = 0; j < (baseTileMap.size.y); y++, j++)
{
tileData[i, j] = new TileData(); //sets the tile in the 2D array to the object
Vector3Int vect = new Vector3Int(i - Mathf.Abs(baseTileMap.origin.x), j - Mathf.Abs(baseTileMap.origin.y), 0);
// if there is a tile this sets the data
if (baseTileMap.GetTile(vect))
{
tileData[i, j].TileName = baseTileMap.GetTile(vect).name;
if (baseTileMap.GetTile(vect).name == "Grass")
{
tileData[i, j].Diggable= true;
}
}
}
}
}```
2 things I can think of:
- Does the animation have a transition time
- Can the fall animation interrupt the jump animation or does the jump animation finish before transition?
Thanks the problem was the transition time
Is there anything built in that lets you serialize Animator's state reference?
errors are fine as long as it still works right?
Errors should always be fixed, warning can be ignored but shouldn't unless you know what you are doing
damn, sometimes iโll have something in a if statement checking if something exists and itโll say not set or whatever
Do you have something right now? If you post the error I might be able to help
Nah iโm just speaking in general
I think itโs when iโm trying to find a script on a gameobject, and i put it in the if parenthesis but it doesnโt exist which is the point of the if statement and it throws an error
Hey guys I have used addforce 2d.force and it keeps the jump faster and faster when i tap it is there any fix so it just jumps a spefic height and the force doesn't keep increasing
nice! pretty much what I've done in the past!
This article may help you: https://gamedevbeginner.com/how-to-jump-in-unity-with-or-without-physics/ - 2D or 3D, jumping is always the same, since gravity and vertical movement is always changing the Y-axis
Okk thank u
i really have no idea how to simulate car navmeshagent. any ideas?
turns look awful for cars
Funny enough, the solution ended up being not using a canvas at all and now it lines up pretty well!
Thanks for the help!
Maybe it's too early, or maybe I'm just being dumb, but how can these two lines...
gameSetup = new GameSetupState(this);
Debug.Log("gameSetup = " + gameSetup.ToString());
End up printing gameSetup = null?
Is that class a Monobehaviour?
You cannot create Monobehaviours with new
It's not.
Can you show the code for that class?
I think you just overrode ToString
If it was really null that would be an exception
Oh wait! ๐ต It is. I forgot to remove the MonoBehaviour inheritance from the base class. Thanks!
Hi, I'm working on a asymmetrical PC/Android-VR project and I have this piece of code that works just fine on PC but won't work on Android, my GameObject is never found and I don't understand why.. Is GameObject.Find() broken on Android platform?
GameObject leftWrist;
private void Update()
{
if (!leftWrist && GameObject.Find("Left Wrist"))
{
leftWrist = GameObject.Find("Left Wrist");
Debug.Log("Left Wrist found !");
}
else
{
Debug.Log("Left Wrist not found !");
}
if (leftWrist)
{
Debug.Log(leftWrist.transform.position);
gameObject.transform.localPosition = leftWrist.transform.position;
gameObject.transform.localRotation = leftWrist.transform.rotation;
}
}
Likely not but rather perhaps leftWrist was and continues to be null
How're you debugging this?
Relative to platform
Show errors/logs etc
This is super inefficient, especially for mobile btw
https://cdn.discordapp.com/attachments/763495187787677697/1077724872383414282/2023-02-21_22-53-22.mp4
https://cdn.discordapp.com/attachments/763495187787677697/1077725196858957974/2023-02-21_22-54-48.mp4
Hey guys, im having an issue with my code here where it works without a problem in the editor, but it breaks in the build?
Likely just a script execution order issue or something though
regarding the rotation of the arm, it flips for like a single frame
i've had this issue since i started this project and i want to try and finally put it to rest
here is the code, labeled with the arm and player code
if anyone could provide insight that would be much appreceiated
I have an in-game console, only the "not found" log appears
I know .Find() isn't the most efficient thing but the gameobject that I am searching for is instantiated on a Network startup, can't think of a better option right now
could just make a public variable tho, that would also work
Even if using Find I don't recommend doing it twice like that.
Better options:
- pass the reference directly from the script that spawns it to here
- have it fire an event when it spawns
- use FindWithTag
- at least use a variable so you don't call Find twice every frame
Or pass it down to relevant script with events or initialization constructor. And also you can cache it with private variable to prevent expensive op every frame.
If that script is useless without the wrist, it should be constructed when the wrist is initialized anyways.
How are you certain the other object exists?
The thing is, the wrist is spawned in a ServerRpc, so I suppose the best choice would be to make leftWrist into a NetworkVariable and set its data directly in my spawning Rpc
Place a debug log in the other object to print that it's been successfully instantiated etc
If the other object does not exist, this function would not be at fault.
it works on PC and this leftWrist is a joint used for hand-tracking and I can literally see them
Ensure the other object exists else we could be adventuring on a wild goose chase.
the problem probably comes from the fact these joints are instantiated in a ServerRpc, and only work on PC as it is the server
I'm implying that the problem lies elsewhere and that Find works as it should.
I'll have to see that tomorrow unfortunately, I'll keep it updated, but you're right I'll investigate on that @dusk apex
anyone know what might be goin on here?
Yes, try scaling only localScale.x instead of all.
That looks like it would flip y rotation as well, maybe that's why the hand flips up? Idk.
Wait I thought the transform is flipped with FlipSprite() method, but it isn't used.
I would use SpriteRenderer.flipX = toggle;
Since usually messing with transform scale isn't recommended
flipsprite doesnt work, it only seems to flip the sprite but none of the children
Cache the children as well
cache in what sense
Does anyone else have this massive textwrap problem when using the UI Builder's text field element?
i just dont understand because it works fine in the editor, but not in the build?
Cache all the sprite renderer and flip. And usually you want to separate the game logic object and actor.
sorry im a bit confused by what you mean
game logic object and actor?
i used scale because it meant that all the children locations moved accordingly
Yeah, like this.
โโโ Player/
โโโ Model/
โ โโโ Base
โ โโโ Hand/
โ โ โโโ Weapon
โ โโโ Feet
โโโ Other Stuff
โโโ Other Stuff
So whatever you do in the graphic side, wouldn't interfere with the gameplay.
Like scaling transform have a lot of issues.
I have a parent gameobject called Parent, and a child that is a button. Is it possible to set the button's onClick() method to a method in the script attached as a component to the Parent?
Just cache all sprite renderer and flip them.
class Actor : MonoBehaviour
{
private SpriteRenderer _hand;
private SpriteRenderer _body;
private void FlipSprite(bool toggle)
{
_hand.FlipY = toggle;
_body.FlipX = toggle;
}
}
Because when I drag the parent gameobject (which has the script attached as a component) to the button's onclick I see the correct script listed, but not the correct functions within the script.
But flipping the sprite would keep all children locations the same wouldn't it?
You can flip the transform too like you currently do (For X rotation), then FlipY() to fix that underhand grip thing.
Fixed by flipping vertical
Even with stack trace its not showing anything
thanks, will try this
first question is are you using the job system yourself explicitly?
I have a few systems using the job system, but I am not sure if it's the cause.
Since all of them complete the schedule on the same frame.
Well one option is to bisect the problem rather than relying on Unity's tooling here
disable half the jobs, etc until the warning stops appearing
I'm trying to find all ScriptableObject assets in my project that implement a certain interface. Since interfaces can't (and probably shouldn't be able to) be serialized, this is the workaround I've come up with. It's not pretty though. It uses Resources.LoadAll<>(), casting and null checks. Does anyone have another suggestion? https://pastebin.com/0tk4tVN8
Its very random though, sometimes it appears, sometimes it never appears. And its always the same 63 number even if there is no 63 objects using the job.
I'll give it a try
I'm not sure if there's a better approach re: Resources.Load, but you can clean the code up slightly with:
if (assets[i] is IWeapon weapon)
{
weapons.Add(weapon);
}```
yeah that's going to make it annoying ๐
Oh, thank you!
one other thing I would suggest is to make sure you're using the using keyword whenever possible to handle any native collections you're creating, rather than manually calling Dispose()
Wait how does this work? I've been disposing them manually, any samples?
I read about it, its very interesting
using () {}
Old syntax:
using (NativeArray<Something> arr = new NativeArray<Something>(blah blah)) {
// do things using the NativeArray here
} // after this closing bracket, it will be disposed automatically, even if there's an exception or error inside.```
New syntax:
```cs
using NativeArray<Something> arr = new NativeArray<Something>(blah blah);
// Do things with the NativeArray here...
// after `arr` falls out of scope, it will be disposed automatically
If you are creating and disposing the collection in the same scope, you should always prefer using over manually disposing since:
- it shows clear intention better
- there's no risk of a logical error or exception leading to un-disposed collection
Also note that using works for any type that implements IDisposable
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
Another common use case for it is when using things like the Stream api:
https://learn.microsoft.com/en-us/dotnet/api/system.io.stream?view=net-7.0
e.g. FileStream etc
also for network connections
again - anything that implements IDisposable
I like the old syntax if I'd want to ensure that the object is release sometime before the end of the method scope - although I've found little to no practical uses so far.
New syntax aligns well with less indentation - a good thing in-itself.
I do think the compiler will dispose it right after its last usage in the scope, but not sure. Definitely a bit more explicit that way
Hey guys, i have a question that has been revolving my mind for quite a while.
Is there a way to get where the image actually begins instead of the Object itself? I know i could try and get the pivot point and play around with it, but just wanted to know if there was an easier way
Multiple native array in old syntax will be indentation hell
Hey, I'm having trouble with my rb2d behaving strangely. If i dont have the gameobject selected in the inspector, drag and friction just completely disappear. I'm wondering if anyone else has had this problem before or has any advice?
I think new syntax is way better
Giving some more info, just trying to build a grid system that really stays on top of the actual image, not the Obj itself.
I'd say it's likely your code is just framerate dependent and having a Rigidbody inspector open is notoriously resource intensive, reducing your framerate
Yup, that's it. Thanks.
How do I make my bat in an arkanoid-type game to cause the ball to have more x velocity the closer it is to the edge of the bat?
Hey guys! I'm coding an Inventory System and a doubt showed up.
this is all im using for the instance.
private struct InventoryEntry
{
public ItemSO item;
public int stackAmount;
};
private Dictionary<int, InventoryEntry> items;
public void AddItem(ItemSO item, int qnt)
{
int entryIndex = GetFirstFreeIndex(item);
if (entryIndex > 0)
{
//then we have a free slot for this item in our inventory
InventoryEntry entry = items[entryIndex];
//whenever we can add to an entry without any problem
if (entry.stackAmount + qnt < item.maxStackQnt)
{
entry.stackAmount += qnt;
return;
}
int amountToAdd = item.maxStackQnt - entry.stackAmount;
int leftover = qnt - amountToAdd;
entry.stackAmount = item.maxStackQnt;
AddItem(item, leftover);
}
//eighter we don't have a free space in the inventory, or we dont have the item. eighter case we need to create a new entry
CreateNewEntry(item, qnt);
}
whenever i do
InventoryEntry entry = items[entryIndex];
am I copying item[entryIndex] and then changing the copy on the rest of the function or am I changing whats inside of my dictionary?
measuere the disatnce from the hit point to the center and use a remapping function
you are making a copy
because InventoryEntry is a struct
changes to that copy will not affect what's in the Dictionary
unless/until you copy it back in explicitly
How do I keep the bouncing normal on the sides then?
my fears have become reality then
Two options:
- always copy your changes back into the Dictionary
- switch it to a
class
i should make it into a class right
yeah
any idea on what would be more efficient?
copying back will use CPU power while class will use more ram right?
it depends on the access pattern, but if you are frequently fectching these things from the Dictionary, modifying them,. copying them back, etc, a class can be much faster
The class is passed around by a single pointer. The struct has to be copied completely each time (though it is only one pointer plus an int so not that much bigger than a pointer)
yeah, makes sense. also if my inventories grow it will get increasingly slower
On the other hand if you are frequently creating and discarding these objects, the class has the potential to be slower because the instances will have to be allocated on the heap and later garbage collected
so - it depends ๐
if I set the enabled variable inside my scritp to false, does the OnDisable() be called?
yes
assuming the script was previously enabled
yeah... i might just call
items[entryIndex] = entry;
after any change it should be good. Right? No need to copy the entire dictionary
new input system:
when i am pressing the button on my gamepad, it is registering as a press and hold rather than a single press down.
so i have to tap extremely fast each time for my double jump to work.
i
want it so if i press once and even hold, it only registers as 1 press so i can do it again, how can i do this?
go into the input system manager or configurations and change the settings for the double tap
yes this will work. You just have to be careful to do it anywhere you're making changes to things
Yeah. Thought so.
Very helpful and always!
this is the default
just make sure you're only looking for performed and not other phases
I wonder why TransformAccess in IJobParallelForTransform is not using the high performance maths.
Vector3, Quaternion
because the intent of that API was to preserve the Transform API as closely as possible
it's supposed to feel like working with a regular Transform
But its used in a job, and the old Vector3/Quaternion cannot be bursted right?
I'm not sure how true that statement is ๐ค
But maybe
If that's the case I guess Unity took the tradeoff of a more familiar API over performance
They may also be converting your V3s/Quats to the Unity.Mathematics types under the hood so the exposure to those types is somewhat limited.
You can do the same in your code too
at worst then there's one copy of the data from those types to the burstable types
But this would mean they're encouraging the old maths library in a job which is not designed to be bursted.
Like if you access transformAccess.rotation.eulerAngles, it uses the old lib
yes
In editor, is it possible to load an asset that is for a different platform than my current settings? Example use case I would like to enumerate textures for all my platforms and grab the compressed texture data
I also believe TransformAccess predates the general availability of Unity.Mathematics somewhat, so that may have played into the decision as well.
would it be possible to make it so that if you did something in the game it would change on a website?
everything is possible ๐
how would one do that? is there any tutorials... i dont even know what to search
how to change website through unity script?
or unity game
you'd have to create a web application - which a whole separate discipline from Unity.
Then your Unity game can simply make a web request to your web app to make whatever change you want it to make
The Q to q cast ends up very awkward, I hope it isn't costly.
it's a copy of 16 bytes
float4 q = transform.rotation;``` might just work
I know
quaternion q = transform.rotation;``` works
Haha, but I will need to access q.value.x q.value.z q.value.w q.value.y individually
For calculating pitch
That's 4x accessing q.value
which you can do right after this, no?
I guess accessing the field is better than double casting
quaternion q = transform.rotation;
float pitch = math.degrees(math.asin(-2.0f * (q.value.x * q.value.z - q.value.w * q.value.y)));
don't you need to access the fields no matter what?
What does float4 get you that quaternion doesn't ๐ค
Should just be cs Quaternion q = ... float pitch = ... (q.x * q.z - q.w * q.y) ...
Just like that of Vector4
There is no quaternion.x/y/z/w
Maybe you're referring to some predefined type?
I mean, on the Unity.Mathematics quaternion
Direct access only through its float4 field.
transform.rotation should be a Quaternion though 
Why not regular Unity Quaternion?
You want to use the new mathematics as much as possible in jobs
They are made to be bursted
Ah, alright. Are there any statistics on this?
Yeah, I'm reading that as of this moment but do not see any data on performances 
Just some red flags like v1.0 and NOTICE: The API is a work in progress and we may introduce breaking changes (API and underlying behavior)
Reminds me of Unity.UI but ๐คทโโ๏ธ
Guess we've got little choices
I'd like to see some profiling on this ๐ (optimistic not sarcasm)
@wild nebula Are you using DOTS? https://forum.unity.com/threads/using-unity-mathematics-without-burst-much-slower-than-mathf.1181269/
I am using it in a bursted jobs
Hey, GitHub Copilot in Visual Studio 2022 is extremly weird for me
It was way better in Visual Studio Code
Is there any kind of fix for this?
To enable or disable IntelliCode preview features, choose Tools > Options > IntelliCode. Under Preview Features, choose Enable, Disable, or Default to configure each feature.
Try this?
It does get in the way
Do I have to restart vs?
Doesn't seem to work :(
Oh and also it's a bit weird with the libraries too
for example, it doesn't know game objects - that could be the issue
aahhhh nvm I've got it working
Is there a way to run a method from a different script without having to reference the script, for example a method called add, is there a way i could call the method in a different script just by putting Add instead of having to do Script.Add
There's a way if the method is static, otherwise nope
Could make an Add() method in this script, that just calls the Add method of the other script
private void Add() => other.Add();
So i could if i just made the method static?
oh
Know the complications of making things static, though
They cannot reference non-static members anymore
I was tryna see if there was a way without having to add anything else to the script though, just calling the method and thatโs it
What about unitys methods
You donโt gotta reference the unity script for those
You mean like Vector3.Lerp() for example?
yea
Sure thing, these are static methods so you can just plug a using static UnityEngine.Vector3; at the top
ah damn
Then you can just call Lerp()
I think it should be alright if the method im thinking of is static
I donโt see why iโd have more then one instance of it
Could someone give me some advice on the best way to hold all of my possible items. I need a way to say "Add this item to the inventory" Only way I could think of was to manually add each scriptable object into a list and use the ID to add them
definitely not
thatโs possibly the worst way, i use a raycast to detect what item it is the players trying to pickup
I don't think that's their question
maybe not
It's more like
How can I reference all my ScriptableObjects that are in my Assets, from code
why though
yea i donโt see how thatโd be helpful for a inventory
oh
idk how to reference assets
They can be put in a Resources folder and be loaded in with a Resources.LoadAll call
Yeah so I have a list of items, and I want to be able to dynamically say "Grass" or whatever
You can build a map, that maps object names to the asset
At the moment I just have an array but I have to know the ID and then the moment the array moves around everything breaks.
Gotcha
Look into Dictionary<string, T>, where T is your ScriptableObject type
You populate it once when the game starts, then you can index it like arrays, but using a string
So I could use a resources folder, load in all the items using LoadAll and then put them into a dictionary with a string as the key?
Precisely
Cool, thanks a bunch. Been stuck for a while thought it was a silly question ๐
How badly did i make this? https://gdl.space/inivixikak.cs
I've seen worse. Way too much use of GameObject references when direct component references would suffice and be more concise/performant
what
I donโt think we have the same line 108
Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 1000)).x```
For some reason it gives me -1000 at the left corner of screen and 1000 at the right one. I'm trying to get the point my mouse is pointing to tho... How do I fix it?
for example:
Debug.Log(HoveredObject.collider.GetComponent<RestrictedSlot>().IsObject);
if (HoveredObject.collider.GetComponent<RestrictedSlot>().IsObject)
{
RestrictedSlotType.Add(HoveredObject.collider.gameObject, HoveredObject.collider.gameObject.GetComponent<RestrictedSlot>().SlotType);
ItemType = RestrictedSlotType[HoveredObject.collider.gameObject].ToString();
Debug.Log(RestrictedSlotType[HoveredObject.collider.gameObject].ToString());
}
if (!HoveredObject.collider.GetComponent<RestrictedSlot>())
{
Items.Add(HoveredObject.rigidbody.gameObject);
ItemIndex += 1;```
Good lord just store a reference to the `RestrictedSlot` directly. It would cut out 50% of this code.
Don't use RaycastHit as some sort of storage medium either. Pull the thing you need out of it and discard it.
if (Input.GetKeyDown(KeyCode.F) && HoveredObject.transform != null && HoveredObject.transform.parent.name == "GrabbableObjects")
Yes we do
Line 92, you can use !InvMenu.activeSelf instead of that comparison to false
Tags would be an improvement
Oh i could just put a tag on the grabbableobject gameobject and then find that object off the tag and get its children
https://paste.ofcode.org/tDQGUcjmw8zMgTU3djVeZw
Hey i do NOT know what is wrong with my script, it's a little save manager but it says "sepcified cast not valid on line 214"... so yeah my whole save is kaboom now :(
it would really help if you provided the whole file
why cut off the important things ๐ข
i looked it up on the pasteofcode
just provide the full actual script and the full actual error message please ๐
Well, not a T specifically, but whatever type argument you provided to that method
https://paste.ofcode.org/b5LDx7FpGxBPb6vjqFm3Gj
line 228 is it now on
Example: GetData<int>("sample") - it wasn't an int for the key "sample"
i checked my set and get lines they all matched
Hello! I was hoping to get some insight on different ways to subscribe to actions / input system via script. I've gathered a few ways to subscribe and I'm not sure when to use which ones. For my situation, I want to call a function when the action has been performed but would rather not pass the CallbackContext as a parameter.
_ActionMap._Action.performed += _Method; // where _Method(InputAction.CallbackContext context)
// B: _Method doesn't need to take the callback context but can't unsubscribe from .performed (-=)
_ActionMap._Action.performed += _ => _Method; // where _Method doesn't take any parameters
// C: best option? downsides?
_ActionMap._ACtion.performed += delegate { _Method(); }; // where _Method doesn't take any parameters
Try logging the type of the value
how would i go around logging types? never done it before hehe sorry
How do I get which position is my mouse over? I use this code
Vector2 mousePos = _inputAction.ReadValue<Vector2>();
Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.nearClipPlane));```
But instead I get values which are heavily dependant on the Z parameter of the vector3. Like if it's 1000, I get 1000 at the right corner of my screen, if it's 1, then 1. ๐ฅฒ
Store the value in a variable first, then log v.GetType()
okk
hey, so i have the issue im hoping someone else was met with too. so, basically, when the example collider with rigidbody falls on another collider with gravity being the only force moving it, all collisions are detected with around a second delay. the problem does not occur when the gameobject is moved into the collider via script line, just when it free falls on it. anyone knows how to fix that?
also im detecting this collision with oncollisionenter2d, and as of now the only thing inside that method is debug.log line. in this example collsion is detected late on the static gameobject the collider with rigidbody falls on, but from my previous expirience the situation is the same on the collider with rigidbody itself
wdym by "all collisions are detected with around a second delay."?
What kind of "detection" are we talking about?
oh sorry I see the second paragraph
how are you measuring this 1s delay
No, and no
Int64 is long and double and float are two different types
shi
well it might not be precise. by that i ment there is a significant, visible delay after the collsion before i can see debug.log message being executed
int is Int32, and float is Single
shouldn't be
should be pretty much instant
i'll see what i can change
it definitely should
Prefer solution 1, as you can unsubscribe. Declare the parameter, but don't use it.
You could also proxy the method and discard the parameter in the process:
... += Method;
// where
void Method(CallbackContext ctx) => RealMethod();
can you show a video perhaps, showing the scene and the issue, and the code?
im suspecting its like a unity bug or something and im not sure what to do about it
I kind of doubt it ๐ but always possible
that would be a serious obvious bug that affects almost everyone
setting to a dictionary must be nullable, and single is not nullable. At least that is what visual studio says :(
don't be vague
show the code, show the error, in full
i am trying not to
sure! the video might be tough as my obs refuses to work, or at least it might take me a minute to record it
It should not matter. object can store anything. As long as you put an <int> in and get an <int> out of yur generic methods, it will work
i put an int in and expect an int out in my code
thats the code. pretty basic. just simple oncollsionenter
right so you're calling e.g. return GetData(key, defaultValue); where defaultValue is a string but the actual value in the dictionary is a long aka Int64 so when it tries to cast it can't because that cast is not valid.
can't convert long to string
@simple egret Thanks for the help got my dict working ๐
The code says otherwise, make sure you really pass an int. C# lets you omit the type argument like this: GetData("a", 42). It will infer the type from the arguments, here int because it saw 42
What would be the downside to option C using the delegate? Could you not just unsubscribe as such:
The delegate { } syntax is the father of the lambda expressions
Lambdas were introduced later on, and couldn't be implicitly converted to delegate types at first
private float elapsedTime;
void OnLevelComplete(){
//save best time for player
if (elapsedTime < Yakapedia.GetFloat($"LevelBestTime {IsNull(currentLevel)}") || !Yakapedia.HasKey($"LevelBestTime {IsNull(currentLevel)}"))
{
Yakapedia.SetFloat($"LevelBestTime {IsNull(currentLevel)}", elapsedTime);
}
}
this is in my levelmanager, calling getfloat and setfloat should work? Because elapsedTime is a float
Yes, it should be alright. Can you post the full error message? So the call that threw the error is shown
yeah the call stack is needed
well the errors are all over the place
i cant move my character because i cant get the selected skin, cant get to the other level because my currentlevel cant be loaded
The first one will do
Select it and the full error will be displayed below the console
Hi guys, i am trying to make a top down game where character is surrounded by dense fog, and i am wondering, how can i make this kind of fog that is surrounded by player and gets distracted by any light/gameobject in scene? I tried to look it up on youtube, but i cant find anything of it on yt. I guess im kind of original
manager.cs:37 would be the best place to start I think. and/or playermanager:93
then we get here
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.transform.CompareTag("Portal"))
{
manager.SelectLevel(manager.currentLevel + 1, true, true, false, false);
}
}
and SelectLevel?
Okay currentLevel is an int, confirm?
but currentlevel is nothing because is cant get it
yup
Then next, Manager:37
if(levelID > Yakapedia.GetInt("CurrentLevel"))
{
MarkLevelAsCompleted();
}
tadaa
that is why SelectLevel doesnt work
Check all the places where you modify the value of the key "CurrentLevel"
Where are you doing SetSomething("CurrentLevel")
and is it ever anything besides int?
public void MarkLevelAsCompleted() => Yakapedia.SetInt("CurrentLevel", Yakapedia.GetInt("CurrentLevel") + 1);
on collision with the portal
Anywhere else?
is that the only place? Serach for CurrentLevel
In all files, Ctrl + Shift + F
LevelUnlocker (basically manager in main menu)
int ProgressInt;
//in start
ProgressInt = Yakapedia.GetInt("CurrentLevel");
Anything that sets, not gets
only that
I suspect the problem here is that when you read/write from json
it doesn't have type information
and just assumes all the numbers are long and double
Ah, it's saved to JSON, so yeah it might
i.e. this:
data = JsonConvert.DeserializeObject<Dictionary<string, object>>(decryptedData);
deserializing to Dictionary<string, object> is dicey
I dont trust visual studios auto code thing
oh btw im using Newtonsoft.Json because JsonUtility is not good lmao
we gathered that
hence JsonConvert
yeh
the thing that is printing out System.Int64 is what/where exactly btw?
let me check real quick
I actually do think casting an Int64 to an Int32 is generally fine ๐ค
with an explicit cast (and acknowledgement of overflow risk)
so I'm a little confused
oh yeah from the Debug.Log in GetData<t>()
can you show how you wrote that Debug.Log
Debug.Log(values[key].GetType());
ok
Yeah it deserializes as long
yeah so - shouldn't you be able to cast that to int? ๐ค
See https://dotnetfiddle.net/7dCmPZ, hit run and look at the dump at the bottom
same with float and string
int64.. huh json is really deserializing it wrong
I'm wondering why changing the value of fallSpeedReduction dosn't actually affect fall speed. I can set it to 0, or 1000 and the result is the same. I am trying to create a bit of a "hover" mechanic but it's giving me a hard time, The hover fall is too slow and I cant seem to change it:
` if(isGrounded)
{
canHover = false;
}
if(Input.GetButtonDown("Jump") && (isGrounded))
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
AudioManager.instance.PlaySFX(10);
}
if(Input.GetButtonUp("Jump"))
{
canHover = true;
}
if(Input.GetButton("Jump") && (!isGrounded) && (canHover))
{
theRB.velocity = new Vector2(theRB.velocity.x, 0);
theRB.AddForce(Vector2.up * fallSpeedReduction * Time.deltaTime);
}`
It's deserializing into a type that's less likely to fail for bigger numbers
well there's no information in the json itself to tell it what type to use so it's guessing
This is kind of why using object is bad practice and it's usually better to use concrete types
then getting and setting to the dictionary would be a pain....
anybody familiar with leantween could possibly illuminate me? i'm trying to build sequences, and for each step in the sequence, i want to add potentially movement, alpha, scaling, etc. i'm using insert which to my understanding should run all the tweens simultaneously until the next append() when it will run that one subsequently, but for whatever reason, the movement is happening first, and then the other tweens, idk why. i've tried a number of things.
_sequence.insert(LeanTween.moveLocal(gameObject, s.Position, s.Duration).setEaseInOutSine());
_sequence.insert(LeanTween.scale(gameObject, s.Scale._to, s.Duration).setEaseInOutSine());
One hacky thing you can try is:
private static T GetData<T>(string key, T defaultValue)
{
if (values.ContainsKey(key))
{
object val = values[key];
return (T)System.Convert.ChangeType(val, typeof(T));
}
return defaultValue;
}```
@swift falcon
hacky idc as long as it works lmao
ill try it one sec
thanks btw
no errors
and my save file picks up the stars
and the fastest time
Welp that was it haha thanks ^^
Is there a way to add tags to the tag list through a script?
Nope
if you need some dynamic tagging system, use a custom component
What I have right now would require the tag and another thing to be the same
I'm not sure what that means
Seems like a poor approach
Yea
to whatever problem you're trying to solve
Which is why I was trying to add tags via script
what is the problem you are trying to solve
Asking about your attempted solution rather than your actual problem
Well its a bit complicated
Which is why I didnt say what Im trying to do
I have a struct, thats acting like a list, and you can set a slot in the list to a specific type, head, body etc. And I'm trying to determine if a object matches that specific type
Based on the tag
In the code whenever the player moves they will face that direction semi-smoothly and it will just do a 360 when passing 0.
What I think is because it isn't taking the angles into account it just goes to the number but I don't know how I could make it use the angle and make it rotate accordingly
The code:
if(movement != Vector3.zero){
transform.rotation = Quaternion.Euler(Vector3.Lerp(transform.eulerAngles, new Vector3(0, cam.eulerAngles.y), 20 * Time.smoothDeltaTime));
}
rather than lerping euler angles, just Slerp the quaternions and it will always take the shortest path. E.g.:
if(movement != Vector3.zero){
Quaternion targetRotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(cam.forward, Vector3.up));
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 20 * Time.smoothDeltaTime);
}```
this is a pitfall of euler angles
thank you so much I will try that now
It worked flawlessly thank you so much!
hey I'm messing around with a canvas and I've given it a canvas scalar. I want it to match the height of the screen so I try to use ScreenMatchMode.MatchWidthOrHeight and matchWidthOrHeight = 1.0f but this changes the localScale of my canvas gameobject which in turn scales any gameobject I parent to the canvas so anything parented to the canvas looks incorrect. anyone know how to prevent this weird localScale issue?
im probably dumb but i dont know the solution for this becou there is only ONE line that doing this error
did you forget to assign PlayerListItemPrefab?
"Friends don't let friends use Euler Angles" pass it on ๐
no
what about GetComponent? you sure that doesn't return null?
try to use Debug.Log() for the different variables and values that could be null
Yeah the one thing that could be null here is what GetComponent returns
Meaning that prefab clone didn't have a PlayerListItem attached
your prefab doesn't have a PlayerListItem component on it.
You can solve this AND clean your code up (remove the GetComponent call entirely) by switching the type of PlayerListItemPrefab to PlayerListItem instead of GameObject and reassigning the prefab
it does
i have the component on it
Got it
it was my unity buging
it was there but unity was removing that every time i hit play
but thx for help guys
il try do that
Nah Unity doesn't remove components on its own unless you tell it to do so
I never saw it do that myself
unity is doing some wiierd shit when its runing 10h plus nonstop
You probably had a Destroy() call somewhere you forgot about
i ahve to constantli restart unity
cuz some thime is giving some random error eventho everythings fine and just restarting unity fix it
Yeah that happens sometimes. Random object destructions, not so often (ie. never)
when my frieend was seting conecting buletholes in hierarchy to the object he shot it was removing the script whery time he pressed play
so he had to restart it
It's your code. Again, no way a bug that critical would slip through testing
You can admit it, everyone makes mistakes
Never happened to me personally, and we never had any issues like this in this discord server for the past 2 years that I know of
im not joking
i liketerakly send the crean that i ahve the script atached to the prefab max 1min after he said prob like 30 sec
and i just tried to restart and it worked
I have a really quick question, Im making top down game and I need the player to show up in front of NPCS when its lower than the NPCS and then vice versa, I know how to do this in like love and and other less graphical APIs but i have like no clue what im doing in unity lol
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Tank you
So I'm coming across a lot of situations where I have a number of gameobjects grouped together in some UI element (imagine a grid-like inventory menu).
I want to have it so when I click an item, it gets highlighted in some way, and any other gameobjects in this element that are highlighted are now no longer highlighted. What's the best way to handle this?
I need reference to all gameobjects in the UI to potentially shut the highlighting off on them while also turning on the clicked element.
For each element in the collection: shut off the highlighting
Highlight the selected one
Simplest solution
If you can get the index in the collection of the element you clicked, then it's even easier. For-loop over each element, and it's highlighted if i == selectedIndex
Does anyone have any suggestions on loading tile data into my 2D array. I cant have an if statement for each tile type. My only thought would be to have a scriptable object for each tile type that is loaded into a dictionary and then query each tile name against that. Any thoughts?
For starters I would use enum instead of string for the name/ID
Then use a switch, or at least else if
So an if else would be the best way to do it? I thought that would get messy after more than 10 or so tiles
The dictionary approach sounds good to me
Also cache that baseTileMap.GetTile(vect).name into a variable as you have that pretty much everywhere
So basically just.
- Manager class that has all the elements.
- Make some method that takes in the gameobject(s) to highlight.
- Turn off everyone who isn't that gameobject.
- Turn on the highlight for that gameobject.
Ye?
Not sure if the performance boost will be significant, but it'll look cleaner at least
Yep sounds good
Alright. Was basically doing that alright but good to know I'm not doing something dumb.
I've done a thing where each element has a button that has an event to call that Highlight method with it's own gameobject as an argument.
anyone can help me with this problem
It is like I am creating an animation and create a float speed that when it is at 0 it does not run and when it is at 1 it runs and I want to see how to make it 1 when touching the arrows to move and when it is not 0 I don't know if I understand myself
Yeah that's a way to know which object to highlight
// void Highlight(GameObject selected)
foreach (GameObject obj in objects)
{
// Does not compile, replace highlighting with your own
obj.highlighted = obj == selected;
}
guys where can i get help to find problem with micro lags every 10-15 sec? i checked profiler but i don't get why i'm getting lag... All stable functions just getting lag for 22ms for micro second, this cause several bugs for me...
This is the scene view painting. It won't be in a build
I verified in build, i had same problem. I can provide more information
can physics processing cause this lag?
Sure. Anything can. You're hiding the important part though - processing time.
Also, you should profile the build
How can i activate profiler in build?
Instructions are in the Unity manual
Does anyone know how to force recompile all VFX graphs? I've upgraded unity and none of them play until I first hit "edit" on their inspector.
It's a lot of busywork.
Forcing a general recompile doesn't seem to work.
(perhaps it's not recompilation but something that the graph window does)
Maybe select all the relevant assets and "Reimport"?๐ค
Hm, I'll try that again.
I did a "force reserialize" on them but not reimport.
It could also be anything you do in a OnCollisionEnter method for example
The profiler will tell you exactly
And if not, use deep profile
Ty, i'm trying right now adding profiler in build version, but unity wont let me. Searching for error right now. I will pay attention to this method.
Ah-ha! It was that all the prefabs themselves were missing a new field m_AllowInstancing
Even though it defaults to true.
Not sure what happened there.
Hey guys So I'm having an issue with networking where I don't know what is best practice, and how to get it to work correctly. I have "successfully" completed this before by making practically everything but the input buttons a server process, which is not what I want to do, I believe. correct me if I'm wrong. but I have a server setup that spawns a player in a new scene once you select host. The host connects and because it's the server instance everything runs correctly and smoothly. However Whenever I try to network it properly (with an authoritative server) I always end up having to basically make every variable a server variable. This is my third attempt and I've decided to stop right before the problems start, with the RPC calls, and ownership BS. I don't want the client to have ownership, but 1) I want to make sure that the person performing the updates is the client that is connected. 2) I have been trying to limit the amount of information back and forth to the server, so I was going to serialize just the transform. I have a cameracontroller object that controls the actual movement based on the players movement that 3) I was hoping not to send any information to and from the server for. I have implemented 3-4 versions of the different player perspectives that the player can toggle between, so it is an extremely complex set of vector mathematics - But It is working perfectly for "single player style" I just need to figure out what I need to convert, where and when to send it, and the ownerships / access tied to the methods. Can somebody help me through the process?
and also, my builds are taking 3+ mins... I can probably limit the time by using smaller assets? IDK if 3 mins is reasonable. I would assume not, but I do like the looks of better assets, etc. Some reduction in compile time would be great as any time I want to test server/ host configuration stuff, I have to completely rebuild, unless if there is a faster way to rebuild? maybe use VS more? IDK. tips on that would be great.
3 minutes to build what? your game/server? If yes, that's really quick by Unity standard.
okay. cool.
Is there a way to "pre-simulate" physics? In my game, I have a real physical dice roll. It'd be cool if I could animate the Character in such a way as that their attack landed at the precise moment the dice finished rolling (ie their rigidbody.IsSleeping() became true). Can I figure out how long until that will be true in instant-time?
So I have the Host running as it should, but when I add another client the camera gets all messed up for the host (it thinks it's the client camera, but moves the correct player) and can't send anything from the new client. I'm assuming that it's because of my isowner tag in the update method, however, how do you handle ownership, IE multiple clients in a fully authoritative server? how do you check that it's the right client and not update other clients simultaneously? :S
(ManzellBeezy I'm sure that you would need to implement your own custom physics script to do so, with increased gravity and velocity, etc. I don't know where to start, but something like that I don't think is built in - but I could be completely wrong. Unity has surprized me many times. esp. with all the asset store has to offer.
I have a physics degree, but it doesn't seem helpful many times.. lol. I don't understand the units of force, etc.
Is the performance of RawImages + Cameras for UI good, or is it much worst than just rendering a 3D object?
unclear what you mean by that
yes - you can create a physics scene and rapidly iterate the steps in it
Interesting. I'll look into it!
So you can use a RawImage to render a 3D Object using a camera, to place it in a UI grid for example. Is that much worst than just rendering a normal 3D object on screen?
Lets say you have 1 render image per object
So 1 camera per object
I was going to link a docs page but they are quite thin on info on how to create and use them - this is what you're looking for though: https://docs.unity3d.com/ScriptReference/PhysicsScene.html
And that'll be the same physics that gets executed? IE the physics is deterministic?
As long as you compare to results on the same device, it should be.
This looks like it'll get me on the right track. I'm not trajectories but it's the same underlying idea. https://www.youtube.com/watch?v=GLu1T5Y2SSc
In this video, we're creating a trajectory using Unity's new Multiple Physics Scenes in PhysX 3.4.2!
โบ Check Codeer Studio: http://bit.ly/codeerstudio
Unity 2018.3 included an upgrade to the Physics, by upgrading their PhysX to PhysX 3.4.2. This included many new features, including Multiple Physics Scenes, which allows you to separate your ph...
{
Debug.Log("Player has taken damage");
Debug.Log(PlayerHealth);
PlayerHealth -= damage;
if (PlayerHealth <= 0f)
{
Die();
}
}
void Die()
{
Debug.Log("Player has died");
transform.position = respawnPoint.position;
PlayerHealth = startingHealth;
}
}``` small peice of code the die function works for everything other than the respawn point thing
idk what to do
Hi,
is there is a shortcut to clean the console log ?
Is anybody here a authoritarian style server expert?
if you're using a CharacterController on your player you need to either disable/enable it or use Physics.SyncTransforms to be able to teleport it
authoritative*? ๐
Of errors, yes. Of logs, no. Expect reflection and whatnot. Google will provide you how.
lmao, yes @leaden ice I'm tired.
I did google it , there is no official answer
however, there some editor scripts that I can make
There is definitely an answer.. it's not pretty.
but if there is one already built, i would rather go with that one.
There isn't.
using System;
using UnityEditor.ShortcutManagement;
using UnityEngine;
namespace Vertx.Editors
{
internal static class Shortcuts
{
[Shortcut("Clear Console", KeyCode.C, ShortcutModifiers.Control | ShortcutModifiers.Alt | ShortcutModifiers.Shift)]
public static void ClearConsole() => Type.GetType("UnityEditor.LogEntries,UnityEditor")!.GetMethod("Clear")!.Invoke(null, null);
}
}
Thanks ๐
How can I put commands to my game
Donโt cross post
Hi, did anyone ever had the same problem with post processing with an URP project
I've searched online for a long time but nothing to fix this specific problem
Does post processing just not work anymore with URP?
Does anyone have any experience with the Hololens?
Everything was fine, until one build
And now my project runs at 3 fps when it was around 55 before at least
and the only thing I changed between the builds was a line of code that changes the rotation of an object when I press a button
The issue is present from the beginning so it has nothing to do with the button
I'd tried erasing the temp data from the hololens, and building with new names etc
quick! Need the name of a void method that gets called when all Dice from a dice roll are done rolling. Any suggestions?
If your asking for a suggestion on what you could name such a function, it sounds more like an event to me, I tend to start my events with the word "On", or "Execute", and functions that do logic after something that is not an event with "Handle" or "Do" if it returns something then "Get" - with that said, I could suggest maybe "OnEndDiceRolls"
Is there a general school of thought on when to use events vs. method calls? Like you're right, this is basically an Event. Right now I have a "hard event" - a direct method call. Is it better practice to have an event, and then whatever you want to hard code, put that into a method that subscribes to the event?
Im sure S.O.L.I.D practice might have specific guidelines with events vs methods, for me personally, I use events whenever something should be notified of an action, for example if a enemy lands a hit on the player I may want to send a "OnDamageTaken" event cause probably the HUD wants to know about that - a function is better used when logic just needs to happen, and either take no params or the params can all be filled from the caller, same example if the enemy sees the player, the enemy may call AttackPlayer() since nothing needs to know about the attack, just the result of the attack, and only the AI needs to execute a function that they can fill the params for
So - I like to use "scriptable objects as enums" but sometimes I miss being able to refer to an enum by value (ie, "thisConditionEnum > ConditionEnum.Threshhold" or whatever). What are the 'best' ways to grab hard references to a scriptable object (without scouring the filesystem)
Direct serialized reference
hmm let's say you absolutely positively couldn't pass in the reference and needed to grab it on the fly. Is there a sneaky way to stash it in the scriptableobject static?
You could maybe load it from Resources, although that could be slow as your project grows, or you could maybe put them in a singleton and reference them from the singleton, though aside from being "messy" (as in, when possible it would be better to have a direct reference), im not sure if it would be better than Resources, though how exactly are you using a scriptable object as a enum?
So the basic idea of the game is that you roll dice to do stuff like in D&D, except each die face has a qualitative result instead of numerical result ("OK", "Good", "Terrible" etc). There are 7 possible Results, and each die has any number of faces with the various results. so each Result is a scriptable object. They implement IComparable so I know which results are better than others, but I want to say something like if(thisResult > Result.Mediocre)
Heyy, im working on a day / night cycle. And struggling to properly rotate the directional light
{
// cycle is used to flip values to reverse the method
if (transform.rotation.x < 90)
{
cycle = 1;
Debug.Log("TOO LOW ANGLE");
}
if (transform.rotation.x > 270)
{
cycle = -1;
Debug.Log("TOO HIGH ANGLE");
}
Debug.Log(transform.rotation.x);
transform.Rotate(0.5f * cycle, 0, 0);
}
At the start the angle is 89
Problem: according to Debug.Log(transform.rotation.x); the angle and rotation are very wrong. Either it shows that its decreasing, while in the inspector its increasing, either the output, and the actual angle have an increasing difference between them.
Quaternions are so messed up, pls help
"very wrong" as in... extremely right, and you are doing it wrong
you probably want eulerAngles, not rotation
i tried that already ;/ localEulerAngles localRotation...
edit: its not the cycle variable, even when i set to to 1 only, it still rotates backwards
if it confuses you, it's probably more sensible to do something like this instead:
public float Rotation = 89;
void Transition() {
if (Rotation < 90)
cycle = 1;
else if (Rotation > 270)
cycle = -1;
Rotation += 0.5f * cycle;
transform.localEulerAngles = new Vector3(Rotation, 0, 0);
}```
oh, so the easier way is to set euler angles rather than .Rotate()
if you are trying to read from eulerAngles, generally yes
But is there a way to read the exact angle value in the inspector?
eulerAngles is derived from the Quaternion, the value in the inspector only exists in the editor
ooh, so id need to convert it in the code before i actually use it
alr got it, tysm man
How can i only show the road and arrow in the mini map and not everything?
everything surround my minimap will be transparent .
Hmm, for using > or other operators, you may have to do operator overloads: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading
I think it might be overkill, but your approach does make sense, in either case, you could give each SO/Result a weighted value to use either through a GetIsBetter(ResultSO A, ResultSO B) (which I assume is what IComparable is doing for you), or if you do want to use > instead of a function, you can use the weight and assign the weight in the scriptable object itself, that way you can just do number comparisons, but reference that however youd like without needing to know the "weight" when you want to compare - or if the dice holds a list/collection of these SO's you could maybe use their index and get your "if(A > B)" from the dice itself rather than the SO's
- Add an input field to your game that you can add something in, preferable toggleable.
- You try parsing messages that come in and realise that parsing parameters or even optional parameters alongside reflection is a pain in the ass.
- You download Quantum console or a free console if you can't pay for it
Serious answer, step 2 is probably way too difficult to accomplish if you want it to work properly. I talk out of experience (release coming soon btw :o)
is there some way i can pass an enum to spawn a prefab? (like Item.SWORD to spawn a sword?) i was thinking of keeping a dictionary mapping enums to prefabs but idk how i would actually refer to the prefab in code
The Dictionary would have the enum as the key, and a path to the prefab as the value.
Alternatively, fill it in directly with the prefab by making the value a GameObject and filling it in the inspector (although I don't think Dictionaries are properly shown in the inspector so you would need to add a custom script to make that possible).
yea the latter was the issue i was running into
the path mapping is clever though thanks!!
if i have a list in a singleton that stores a gameobj, does the gameobj get destroyed when you load a new scene or does it stay active because there's a reference from the singleton?
Well it's not magically going to be null
But I'm guessing if you start using a reference of a destroyed gameObject Unity is going to shit bricks real quick.
Just properly remove destroyed references
As long as a reference exists, the reference will not be deleted. I assume the reference will not point to a valid game object, and at that point will not work.
thanks!
How do i make a customer editor that makes disappear the serialized fields below text or image based on the enum?
[Serializable]
public class DescriptionData
{
public enum DescriptionType { Text, Image }
[Header("Options")]
[SerializeField] private DescriptionType descriptionType;
[Header("Text")]
[SerializeField] private string descriptionText;
[SerializeField] private bool enableOverrideColor;
[SerializeField] private Color overrideColor = Color.black;
[Header("Image")]
[SerializeField] private Sprite image;
}
For storing item tables and stuff like that, what would be better: Json or Scriptable Objects?
Scriptable Objects if they're just data that won't be modified during run time
Hello everyone. I am currently trying to create a more or less organic shape (box with rounded edges for now). I am struggling with the radiants being calculated depending on the position of the edges. you can see in this screenshot, that in top right and bottom right there are those hard edges, which I want to remove. So I somehow need to calculate the distance of the verts around the corner to increase or decrease depending on (here comes the part) what? I tried angle, I tried dot product but I seem to be just getting lost in prototype code. Maybe someone can lighten up my issue here. The code is adapted from another source, so it is clamped to my needs: https://hatebin.com/zvsknlktfw
Definitely not modified or updated in any way. Just referenced.
Then ScriptableObjects would be fine
the newF value is already doing what I need but only for the right hand side, as its just multiplying pi anyways. But I would need to like rotate the start point AND offset the distance at the same time.
how do i fix jittery movement with rigidbody.moveposition? i am doing it in fixed update:
if (playerMovement != Vector3.zero) // if the left gamepad stick is moving
{
_playerRigidBody.MovePosition(transform.position + _mainCamera.rotation * playerMovement * _jumpHorizontalSpeed * Time.deltaTime);
}
character interpolate is active
are you certain the movement is jittery and not perhaps the camera?