#archived-code-general

1 messages ยท Page 44 of 1

vestal crest
#

i will lose the changes

leaden ice
#

stop using an instance material - that is not the asset you want to change. Change the actual asset you want to change.

vestal crest
#

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

leaden ice
#

You cannot modify assets that are part of the build

vestal crest
#

no

#

i want to do it in editor

leaden ice
#

save the new asset

#

fix the references

vestal crest
#

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

leaden ice
#

serialize the material to json, and deserialize into the original

#

oh actually

vestal crest
#

thanks ill try it as soon as im available

left badge
#

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?

leaden ice
#

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

vestal crest
leaden ice
#

GameObjects are "just identities". Transforms are components on GameObjects which contain position/rotation/scale and parent/child relationship data.

leaden ice
#

??

#

Transforms are "actual components in the world"

vestal crest
leaden ice
#

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

simple egret
leaden ice
#

they render things

simple egret
#

Pretty much the same thing you said in the other channel

leaden ice
#

"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.

simple egret
#

Nothing of this is related to logic or syntax

leaden ice
#

they exist in the world

#

the world is and always has been imaginary

#

it's a video game

vestal crest
leaden ice
#

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?

simple ridge
#

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}");
    }
}```
leaden ice
#

<@&502884371011731486> (nitro scammer)

simple echo
#

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?

leaden ice
simple echo
leaden ice
simple echo
simple echo
leaden ice
#

you're teleporting your player with this script

#

which does not play well with Rigidbody motion

simple echo
leaden ice
leaden ice
#

how do you do what?

leaden ice
#

You place objects with colliders in the world

simple echo
leaden ice
simple echo
#

i have one script for player movement for the player to move left, right, up and down and the other script is for boundaires

simple echo
leaden ice
#

you would place objects in the world with colliders

#

to prevent your player from moving past them

simple echo
simple echo
leaden ice
#

place a GameObject in the scene

#

attach a Collider2D component to it

simple echo
simple echo
leaden ice
#

Wdym? It will be an object that has a collider that acts as a boundary

leaden ice
#

there are only GameObjects

simple echo
leaden ice
#

then attach the collider you want

simple echo
leaden ice
#

if that's what you want

#

you will need at least 4 of them

#

to form the boundaries

simple echo
#

oh

simple echo
leaden ice
#

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.

simple ridge
elfin tree
#

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!

simple egret
#

Change its anchoring preset from the Rect Transform's Inspector

elfin tree
#

I think I set it's pivot already, that should be it?

simple egret
#

Depends on what's needed

#

Stretch so it fills its container object?

elfin tree
#

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

simple egret
#

Also log the .anchoredPosition.

versed marsh
#

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

elfin tree
simple egret
#

Yeah it's the position of the object relative to its anchoring preset

hexed pecan
simple egret
#

Show how said preset is done from the Inspector

versed marsh
elfin tree
simple egret
#

Middle-Center

#

It won't stretch to fill its container

#

Click that square and stretch both axes

hexed pecan
#

Probably works better for what you want

elfin tree
simple egret
#

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

elfin tree
#

Okay, I will play around with that then, so I should probably align it in inspector first and then use margins if needed?

simple egret
#

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

elfin tree
#

Yeah, I guess you meant Shift, will have some experimenting to do then!

simple egret
elfin tree
#

@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.

final lotus
#

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.

simple egret
# elfin tree But the object always moves out of position, it never keeps the same relative on...

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

tame urchin
#

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?

plain coyote
#

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.

vagrant blade
#

Open the prefab, change it like any component.

#

Also not a coding question

plain coyote
plain coyote
plain coyote
simple egret
#

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

plain coyote
#

@simple egret
Thanks,
I tested with new prefab it works,
seems like the old used something other than textmeshpro

tepid river
#

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?

leaden ice
tepid river
#

well phsyics collision with another collider. bouncing off stuff

leaden ice
#

Where is the Rigidbody?

tepid river
#

on the parent

leaden ice
#

You need a Rigidbody to get physical interactions

leaden ice
#

Steamrunner_colliders?

shut ridge
#

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?

tepid river
#

haha alright, found the issue. my collider mesh gets scaled 10 times bigger or something and i had gizmos disabled, so didnt notice

leaden ice
#

Yes colliders are subject to Transform scaling

tepid river
#

correction: for whatever reason the renderers transform is at 0.11 scale after import

leaden ice
#

Renderers are also subject to Transform scaling ๐Ÿ˜‰

ionic socket
#

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?

hollow stone
#

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.

hollow stone
ionic socket
hollow stone
ionic socket
rustic rain
#

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?

hollow stone
rustic rain
#

i dont see how that would help, its not actually an error

hollow stone
#

You never know util you check ๐Ÿ˜…

rustic rain
#

do you see what im talking about here?

#

when the thing does right above or below tthe player it flashes up briefly

hollow stone
#

Possibly something to do with framerate.

rustic rain
#

but in the editor it works perfectly fine

hollow stone
#

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.

rustic rain
#

i mean its going quite fast

hollow stone
#

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.

rustic rain
#

okay, will try this, thank you!

#

any other ideas?

hollow stone
#

I cannot solve this kind of issue with not seeing code. But I think you can try some debugging steps first^^

valid minnow
#

if anyone knows anything about shaders, help in #archived-shaders would be appreciated

rustic rain
#

here is the code for the rotation of the arm

hollow stone
#

Please look on how you should post code here ๐Ÿ˜…

rustic rain
#

soz one moment

hollow stone
#

Does this flip the whole character as well or another script?

rustic rain
#

it will still do it sometimes tho

#

if i dont flip the player arm as well as tthe player it will aim backwards

wind lark
#

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?

hollow stone
rustic rain
#

will try this later

wind lark
#
        /// <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.

somber steeple
#

what do you use to paste code out like that?

somber nacelle
#

!code

tawny elkBOT
#
Posting 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.

wind lark
#

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?

somber nacelle
wind lark
#

im trying to load

#

a .shader in the assetbundle

#

as a shader

#

so i can make a material out of it with script

somber nacelle
#

have you googled it? because the first result when I do is how to load a shader from an asset bundle

somber steeple
somber nacelle
#

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

somber steeple
#

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

somber nacelle
#

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

somber steeple
#

Wait, it worked? thanks, could you explain why it work?

thin frigate
#

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).

buoyant ivy
#

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

ionic socket
#

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?

lime token
#

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

wide burrow
ionic socket
#

yeah N-sided

wide burrow
#

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

celest solstice
#

Has anyone ever made a rhythm game with or without wwise ? I have some questions about how to implement certain stuff

south gorge
#

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--;
    }
ionic socket
south gorge
#

here is a picture of what happens

#

it always goes the same direction from the guy

wide burrow
ionic socket
wide burrow
ionic socket
wide burrow
#

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

ionic socket
tawny elkBOT
#
Posting 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.

ionic socket
wide burrow
#

if you drag the main object into the scene, it should be a gameobject with them as children

ionic socket
#

oy, thank you ๐Ÿ˜›

south gorge
drifting grail
#

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)

wild nebula
#

How do I debug Jobs?

#

This warning points to nowhere

elfin vessel
lyric moon
#

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

elfin vessel
#

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

lyric moon
elfin vessel
#

remap, the name was on the tip of my tongue

elfin vessel
elfin vessel
#

wait why doesn't you menu have those other options

wild nebula
#

I don't know either

elfin vessel
#

that's. odd

wild nebula
#

Nobody found the solution either lol

elfin vessel
#

i love when unity works

wild nebula
#

Its also not on preferences>jobs

elfin vessel
wild nebula
#

Yes, Jobs & Burst

elfin vessel
#

hmm

leaden ice
wild nebula
elfin vessel
#

ooyh good one i forgot about collections

#

that one has nativearrays which is where a lot of leaks come from

wild nebula
#

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'```
leaden ice
#

stupid question but did you install all these packages from package manager, and what versions do you have for each?

leaden ice
#

(and what Unity version are you on?)

wild nebula
leaden ice
#

what version of Unity?

wild nebula
leaden ice
#

Seems like you should be on at least version 1.4 ๐Ÿค”

#

if not 2.1

wild nebula
leaden ice
wild nebula
#

That's strange lol

#

This is the only available option

leaden ice
#

looks like 2.1 is there, as a preview

wild nebula
#

Going preview hmm

#

Ok I'll try

leaden ice
#

Well you're kind of already in "preview" by using 2022 ๐Ÿ˜‰

unreal temple
#

How can I run the unity codemod if I dismissed it when the modal first popped up?

#

For automatic API updating.

ionic socket
wild nebula
#

With all dependencies installed too

#

Haha, I'll just not debug my jobs

unreal temple
ionic socket
#

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"?

leaden ice
#

I think this would give you a more uniform random rotation than picking from a "cube" of euler angles

ionic socket
unreal temple
#

(fwiw I'm sure AngleAxis accepts an axis of any length)

leaden ice
wild nebula
ionic socket
lucid matrix
#

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?

lucid matrix
#

I have tried it

#

This is second day it is happening

rigid island
lucid matrix
#

Yes

lusty dragon
#

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?

earnest epoch
#

Is this a problem better served by using a dictionary?

plucky inlet
analog axle
#

is there a way to turn airdrop with ios app on (10 minutes)

rigid island
analog axle
#

well create a script that turns on/off airdrop on ios xd

#

is it possible?

leaden ice
#

In iOS, sure

spring basin
#

is there a separate thread for Netcode for GameObjects?

analog axle
#

and howโ€ฆ..?

leaden ice
#

Not really a Unity question

analog axle
#

ok sorry

rigid island
analog axle
#

why is it networking tho?,,,

#

idk what it means xd

leaden ice
#

That wasn't directed at you

spring basin
#

thank you

analog axle
#

lol im idiot

analog axle
#

c# script unity code

leaden ice
#

No you need iOS Swift or Objective C code

rigid island
#

there is no iOS specific code in c#

analog axle
#

nerver created ios app xd thats why idk xd

#

but thanks

leaden ice
#

Aside from this

#

It's not Unity related

static tiger
#

Rotation of connected object.

vestal crest
#

what is the best way to move a car along road with navmesh, how to control it at corners

#

when it needs to turn

simple ridge
#

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

charred robin
#

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?

copper plaza
simple ridge
simple ridge
charred robin
#

It's super annoying KEKW

simple ridge
#

Ah damn, yeah that is anoying. Sorry someone else may have a better idea at doing this then I do. Sorry

charred robin
mental rover
#

it doesn't need to be in the external code

charred robin
mental rover
#

why?

charred robin
simple ridge
#

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

mental rover
#

it would be strange to me if that were true and something like an initialise on load script wouldn't be sufficient

simple ridge
#

That way the object you need is already in the scene as you can create it before loading the new one.

mental rover
#

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?

hollow stone
#

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.

deep willow
#

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

mellow sigil
#

Objects are destroyed at the end of the frame

deep willow
#

ah okay

#

how do i get the correct amount before the end of the frame?

mellow sigil
#

unparent the object before destroying it

cloud smelt
#

@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;
                }
            }
        }
    } 
}```
thick heron
#

Why does my fall animation take so long to switch to my idle animation

dusky lake
thick heron
vague slate
#

Is there anything built in that lets you serialize Animator's state reference?

devout solstice
#

errors are fine as long as it still works right?

dusky lake
devout solstice
#

damn, sometimes iโ€™ll have something in a if statement checking if something exists and itโ€™ll say not set or whatever

dusky lake
#

Do you have something right now? If you post the error I might be able to help

devout solstice
#

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

spice aspen
#

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

wintry crescent
soft shard
# spice aspen Hey guys I have used addforce 2d.force and it keeps the jump faster and faster w...

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

Learn how to jump in Unity, how to control jump height, plus how to jump without using physics, in my in-depth beginner's guide.

spice aspen
#

Okk thank u

vestal crest
#

i really have no idea how to simulate car navmeshagent. any ideas?

#

turns look awful for cars

elfin tree
#

Thanks for the help!

sweet raft
#

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?

leaden ice
#

You cannot create Monobehaviours with new

sweet raft
leaden ice
#

I think you just overrode ToString

#

If it was really null that would be an exception

sweet raft
#

Oh wait! ๐Ÿ˜ต It is. I forgot to remove the MonoBehaviour inheritance from the base class. Thanks!

tardy agate
#

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;
        }
    }
dusk apex
#

How're you debugging this?

#

Relative to platform

#

Show errors/logs etc

leaden ice
rustic rain
leaden ice
#

Likely just a script execution order issue or something though

rustic rain
#

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

tardy agate
tardy agate
#

could just make a public variable tho, that would also work

leaden ice
wild nebula
#

If that script is useless without the wrist, it should be constructed when the wrist is initialized anyways.

dusk apex
tardy agate
#

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

dusk apex
#

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.

tardy agate
dusk apex
tardy agate
#

the problem probably comes from the fact these joints are instantiated in a ServerRpc, and only work on PC as it is the server

dusk apex
#

I'm implying that the problem lies elsewhere and that Find works as it should.

tardy agate
#

I'll have to see that tomorrow unfortunately, I'll keep it updated, but you're right I'll investigate on that @dusk apex

rustic rain
wild nebula
#

That looks like it would flip y rotation as well, maybe that's why the hand flips up? Idk.

rustic rain
#

did you look at the code?

#

oh wiat

#

hold on let me try

wild nebula
#

Wait I thought the transform is flipped with FlipSprite() method, but it isn't used.

rustic rain
#

that does this now

wild nebula
#

That's a really cool pose ๐Ÿ˜‚

#

Love it, keep it as feature

rustic rain
#

haha

#

maybe i could use flip sprite or something?

#

idk tho

wild nebula
#

I would use SpriteRenderer.flipX = toggle;

#

Since usually messing with transform scale isn't recommended

rustic rain
#

flipsprite doesnt work, it only seems to flip the sprite but none of the children

wild nebula
#

Cache the children as well

rustic rain
#

cache in what sense

copper torrent
#

Does anyone else have this massive textwrap problem when using the UI Builder's text field element?

rustic rain
#

i just dont understand because it works fine in the editor, but not in the build?

wild nebula
rustic rain
#

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

wild nebula
# rustic rain game logic object and actor?

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.

loud charm
#

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?

wild nebula
#

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;
  }
}
loud charm
#

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.

rustic rain
wild nebula
#

Fixed by flipping vertical

#

Even with stack trace its not showing anything

rustic rain
wild nebula
#

How do I know what's causing the leak??

#

Its not pointing to anything

leaden ice
# wild nebula

first question is are you using the job system yourself explicitly?

wild nebula
#

Since all of them complete the schedule on the same frame.

leaden ice
ionic adder
#

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

wild nebula
#

I'll give it a try

leaden ice
leaden ice
leaden ice
wild nebula
#

I read about it, its very interesting

#

using () {}

leaden ice
# wild nebula Wait how does this work? I've been disposing them manually, any samples?

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

#

also for network connections

#

again - anything that implements IDisposable

dusk apex
#

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.

leaden ice
tired drift
#

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

wild nebula
severe junco
#

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?

wild nebula
#

I think new syntax is way better

tired drift
leaden ice
orchid bane
#

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?

magic harness
#

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?

leaden ice
leaden ice
#

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

orchid bane
magic harness
#

my fears have become reality then

leaden ice
magic harness
#

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?

leaden ice
#

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)

magic harness
#

yeah, makes sense. also if my inventories grow it will get increasingly slower

leaden ice
#

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 ๐Ÿ˜‰

jovial spear
#

if I set the enabled variable inside my scritp to false, does the OnDisable() be called?

leaden ice
#

assuming the script was previously enabled

magic harness
#

yeah... i might just call

  items[entryIndex] = entry;

after any change it should be good. Right? No need to copy the entire dictionary

floral crescent
#

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?

magic harness
#

go into the input system manager or configurations and change the settings for the double tap

leaden ice
magic harness
#

Yeah. Thought so.
Very helpful and always!

leaden ice
#

just make sure you're only looking for performed and not other phases

wild nebula
#

I wonder why TransformAccess in IJobParallelForTransform is not using the high performance maths.

#

Vector3, Quaternion

leaden ice
#

it's supposed to feel like working with a regular Transform

wild nebula
#

But its used in a job, and the old Vector3/Quaternion cannot be bursted right?

leaden ice
#

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

leaden ice
#

at worst then there's one copy of the data from those types to the burstable types

wild nebula
#

Like if you access transformAccess.rotation.eulerAngles, it uses the old lib

leaden ice
#

yes

wild nebula
obsidian tree
#

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

leaden ice
# wild nebula

I also believe TransformAccess predates the general availability of Unity.Mathematics somewhat, so that may have played into the decision as well.

atomic matrix
#

would it be possible to make it so that if you did something in the game it would change on a website?

leaden ice
atomic matrix
#

how would one do that? is there any tutorials... i dont even know what to search

devout solstice
#

or unity game

leaden ice
wild nebula
leaden ice
#
float4 q = transform.rotation;``` might just work
#

I know

quaternion q = transform.rotation;``` works
wild nebula
#

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

leaden ice
wild nebula
#

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)));
leaden ice
dusk apex
#

Just like that of Vector4

wild nebula
dusk apex
#

Maybe you're referring to some predefined type?

wild nebula
#

I mean, on the Unity.Mathematics quaternion

#

Direct access only through its float4 field.

dusk apex
#

transform.rotation should be a Quaternion though UnityChanThink

dusk apex
wild nebula
#

They are made to be bursted

dusk apex
#

Ah, alright. Are there any statistics on this?

dusk apex
#

Yeah, I'm reading that as of this moment but do not see any data on performances UnityChanThink

#

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

wild nebula
#

Haha, its released though, its stable enough :>

dusk apex
#

I'd like to see some profiling on this ๐Ÿ˜ƒ (optimistic not sarcasm)

wild nebula
#

I wish I wasn't lazy to do profiling :>

#

Someone should do it though!

dusk apex
wild nebula
surreal flicker
#

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?

vagrant blade
#

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

surreal flicker
#

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

devout solstice
#

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

simple egret
#

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();
devout solstice
#

So i could if i just made the method static?

devout solstice
simple egret
#

Know the complications of making things static, though

#

They cannot reference non-static members anymore

devout solstice
#

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

simple egret
#

You mean like Vector3.Lerp() for example?

devout solstice
#

yea

simple egret
#

Sure thing, these are static methods so you can just plug a using static UnityEngine.Vector3; at the top

devout solstice
#

ah damn

simple egret
#

Then you can just call Lerp()

devout solstice
#

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

cloud smelt
#

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

devout solstice
#

definitely not

#

thatโ€™s possibly the worst way, i use a raycast to detect what item it is the players trying to pickup

simple egret
#

I don't think that's their question

devout solstice
#

maybe not

simple egret
#

It's more like

How can I reference all my ScriptableObjects that are in my Assets, from code

devout solstice
#

why though

simple egret
#

For an item list, like the question says

#

Think Minecraft's creative inventory

devout solstice
#

yea i donโ€™t see how thatโ€™d be helpful for a inventory

#

oh

#

idk how to reference assets

simple egret
#

They can be put in a Resources folder and be loaded in with a Resources.LoadAll call

cloud smelt
#

Yeah so I have a list of items, and I want to be able to dynamically say "Grass" or whatever

simple egret
#

You can build a map, that maps object names to the asset

cloud smelt
#

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

simple egret
#

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

cloud smelt
#

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?

simple egret
#

Precisely

cloud smelt
#

Cool, thanks a bunch. Been stuck for a while thought it was a silly question ๐Ÿ™‚

devout solstice
leaden ice
devout solstice
#

what

simple egret
#

Line 108, avoid doing logic on object names

#

They can be duplicate, they can change

devout solstice
#

I donโ€™t think we have the same line 108

orchid bane
#
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?
leaden ice
# devout solstice what

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.

simple egret
devout solstice
#

Ah

#

Idk how else to do that

simple egret
#

Line 92, you can use !InvMenu.activeSelf instead of that comparison to false

simple egret
devout solstice
#

Oh i could just put a tag on the grabbableobject gameobject and then find that object off the tag and get its children

swift falcon
leaden ice
#

why cut off the important things ๐Ÿ˜ข

simple egret
#

214 matches the exception being thrown

#

Luck?

swift falcon
#

i looked it up on the pasteofcode

simple egret
#

Okay

#

It means whatever value was in the dictionary at that key, was not a T

leaden ice
simple egret
#

Well, not a T specifically, but whatever type argument you provided to that method

swift falcon
simple egret
#

Example: GetData<int>("sample") - it wasn't an int for the key "sample"

swift falcon
#

i checked my set and get lines they all matched

static oracle
#

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
simple egret
#

Try logging the type of the value

swift falcon
orchid bane
#

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. ๐Ÿฅฒ
simple egret
swift falcon
#

okk

tawny jewel
#

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

leaden ice
#

What kind of "detection" are we talking about?

#

oh sorry I see the second paragraph

#

how are you measuring this 1s delay

swift falcon
#

it says double for float, and int64 for the ints

#

that should match right?

simple egret
#

No, and no

leaden ice
swift falcon
#

shi

tawny jewel
simple egret
#

int is Int32, and float is Single

leaden ice
#

should be pretty much instant

swift falcon
tawny jewel
simple egret
leaden ice
tawny jewel
#

im suspecting its like a unity bug or something and im not sure what to do about it

leaden ice
#

that would be a serious obvious bug that affects almost everyone

swift falcon
#

setting to a dictionary must be nullable, and single is not nullable. At least that is what visual studio says :(

leaden ice
#

show the code, show the error, in full

swift falcon
#

i am trying not to

tawny jewel
swift falcon
simple egret
swift falcon
tawny jewel
leaden ice
# swift falcon

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

cloud smelt
#

@simple egret Thanks for the help got my dict working ๐Ÿ‘

simple egret
static oracle
simple egret
#

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

swift falcon
# simple egret The code says otherwise, make sure you *really* pass an int. C# lets you omit th...
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

simple egret
#

Yes, it should be alright. Can you post the full error message? So the call that threw the error is shown

leaden ice
#

yeah the call stack is needed

swift falcon
#

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

simple egret
#

The first one will do

#

Select it and the full error will be displayed below the console

tepid orchid
#

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

swift falcon
simple egret
#

PlayerManager, line 93 is the root cause

#

Which goes to Manager, line 37

leaden ice
# swift falcon

manager.cs:37 would be the best place to start I think. and/or playermanager:93

swift falcon
#

then we get here

#
    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.transform.CompareTag("Portal"))
        {
            manager.SelectLevel(manager.currentLevel + 1, true, true, false, false);
        }
    }
leaden ice
simple egret
#

Okay currentLevel is an int, confirm?

swift falcon
#

but currentlevel is nothing because is cant get it

swift falcon
simple egret
#

Then next, Manager:37

swift falcon
#
        if(levelID > Yakapedia.GetInt("CurrentLevel"))
        {
            MarkLevelAsCompleted();
        }
#

tadaa

#

that is why SelectLevel doesnt work

simple egret
#

Check all the places where you modify the value of the key "CurrentLevel"

leaden ice
#

and is it ever anything besides int?

swift falcon
#
 public void MarkLevelAsCompleted() => Yakapedia.SetInt("CurrentLevel", Yakapedia.GetInt("CurrentLevel") + 1);

on collision with the portal

simple egret
#

Anywhere else?

leaden ice
#

is that the only place? Serach for CurrentLevel

simple egret
#

In all files, Ctrl + Shift + F

swift falcon
#

LevelUnlocker (basically manager in main menu)

int ProgressInt;

//in start
ProgressInt = Yakapedia.GetInt("CurrentLevel");
simple egret
#

Anything that sets, not gets

simple egret
#

Nah, not possible

#

You can't get a Int64 (long) out of thin air

leaden ice
#

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

simple egret
#

Ah, it's saved to JSON, so yeah it might

leaden ice
#

i.e. this:
data = JsonConvert.DeserializeObject<Dictionary<string, object>>(decryptedData);

devout solstice
#

I feel like this would work

#

But I feel like it wouldnt

leaden ice
#

deserializing to Dictionary<string, object> is dicey

devout solstice
#

I dont trust visual studios auto code thing

swift falcon
leaden ice
#

hence JsonConvert

swift falcon
#

yeh

leaden ice
# swift falcon

the thing that is printing out System.Int64 is what/where exactly btw?

swift falcon
#

let me check real quick

leaden ice
#

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

swift falcon
leaden ice
swift falcon
#

Debug.Log(values[key].GetType());

leaden ice
#

ok

simple egret
#

Yeah it deserializes as long

leaden ice
#

yeah so - shouldn't you be able to cast that to int? ๐Ÿค”

swift falcon
#

maybe int.Parse on GetInt?

simple egret
swift falcon
#

same with float and string

swift falcon
dull kindle
#

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);
            }`
simple egret
leaden ice
swift falcon
#

then getting and setting to the dictionary would be a pain....

ancient cloak
#

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());
leaden ice
#

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
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

swift falcon
devout solstice
#

Is there a way to add tags to the tag list through a script?

leaden ice
#

if you need some dynamic tagging system, use a custom component

devout solstice
#

What I have right now would require the tag and another thing to be the same

leaden ice
#

I'm not sure what that means

devout solstice
#

Like the word

#

The name

leaden ice
#

Seems like a poor approach

devout solstice
#

Yea

leaden ice
#

to whatever problem you're trying to solve

devout solstice
#

Which is why I was trying to add tags via script

leaden ice
#

what is the problem you are trying to solve

leaden ice
devout solstice
#

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

lunar mauve
#

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));
}

leaden ice
#
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

lunar mauve
lunar mauve
kind pivot
#

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?

maiden lake
#

im probably dumb but i dont know the solution for this becou there is only ONE line that doing this error

kind pivot
leaden ice
kind pivot
maiden lake
kind pivot
#

try to use Debug.Log() for the different variables and values that could be null

simple egret
#

Yeah the one thing that could be null here is what GetComponent returns

#

Meaning that prefab clone didn't have a PlayerListItem attached

leaden ice
maiden lake
#

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

simple egret
#

I never saw it do that myself

maiden lake
#

unity is doing some wiierd shit when its runing 10h plus nonstop

simple egret
#

You probably had a Destroy() call somewhere you forgot about

maiden lake
#

i ahve to constantli restart unity

#

cuz some thime is giving some random error eventho everythings fine and just restarting unity fix it

simple egret
#

Yeah that happens sometimes. Random object destructions, not so often (ie. never)

maiden lake
#

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

simple egret
#

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

maiden lake
#

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

pallid sail
#

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

leaden ice
pallid sail
#

Tank you

dawn nebula
#

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.

simple egret
#

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

cloud smelt
#

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?

hexed pecan
#

For starters I would use enum instead of string for the name/ID

#

Then use a switch, or at least else if

cloud smelt
#

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

hexed pecan
#

The dictionary approach sounds good to me

simple egret
#

Also cache that baseTileMap.GetTile(vect).name into a variable as you have that pretty much everywhere

dawn nebula
#

Ye?

simple egret
dawn nebula
# simple egret 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.

frozen gull
#

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

simple egret
rough jacinth
#

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...

leaden ice
rough jacinth
#

I verified in build, i had same problem. I can provide more information

#

can physics processing cause this lag?

cosmic rain
#

Also, you should profile the build

rough jacinth
#

How can i activate profiler in build?

leaden ice
unreal temple
#

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)

cosmic rain
unreal temple
#

I did a "force reserialize" on them but not reimport.

hexed pecan
#

The profiler will tell you exactly

#

And if not, use deep profile

rough jacinth
unreal temple
#

Even though it defaults to true.

#

Not sure what happened there.

sand spade
#

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?

sand spade
#

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.

drowsy salmon
sand spade
#

okay. cool.

ionic socket
#

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?

sand spade
#

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.

elfin tree
#

Is the performance of RawImages + Cameras for UI good, or is it much worst than just rendering a 3D object?

cold parrot
mental rover
ionic socket
elfin tree
#

Lets say you have 1 render image per object

#

So 1 camera per object

mental rover
ionic socket
cosmic rain
#

As long as you compare to results on the same device, it should be.

ionic socket
# mental rover I was going to link a docs page but they are quite thin on info on how to create...

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...

โ–ถ Play video
grim copper
#
    {
        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

solemn raven
#

Hi,
is there is a shortcut to clean the console log ?

sand spade
#

Is anybody here a authoritarian style server expert?

leaden ice
# grim copper idk what to do

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

leaden ice
dusk apex
sand spade
#

lmao, yes @leaden ice I'm tired.

solemn raven
#

however, there some editor scripts that I can make

dusk apex
#

There is definitely an answer.. it's not pretty.

solemn raven
#

but if there is one already built, i would rather go with that one.

dusk apex
#

There isn't.

quartz folio
# solemn raven Hi, is there is a shortcut to clean the console log ?
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);
    }
}
digital umbra
#

How can I put commands to my game

swift falcon
supple hawk
#

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?

thorny spindle
#

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

ionic socket
#

quick! Need the name of a void method that gets called when all Dice from a dice roll are done rolling. Any suggestions?

soft shard
ionic socket
soft shard
# ionic socket Is there a general school of thought on when to use events vs. method calls? Lik...

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

ionic socket
ionic socket
# leaden ice 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?

soft shard
#

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?

ionic socket
#

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)

upbeat dust
#

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

quartz folio
#

"very wrong" as in... extremely right, and you are doing it wrong

#

you probably want eulerAngles, not rotation

upbeat dust
upbeat dust
quartz folio
#

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);
}```
upbeat dust
quartz folio
#

if you are trying to read from eulerAngles, generally yes

upbeat dust
#

But is there a way to read the exact angle value in the inspector?

quartz folio
#

eulerAngles is derived from the Quaternion, the value in the inspector only exists in the editor

upbeat dust
#

alr got it, tysm man

wet condor
#

How can i only show the road and arrow in the mini map and not everything?
everything surround my minimap will be transparent .

soft shard
# ionic socket So the basic idea of the game is that you roll dice to do stuff like in D&D, exc...

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

thin aurora
#
  1. You try parsing messages that come in and realise that parsing parameters or even optional parameters alongside reflection is a pain in the ass.
#
  1. 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)

vale wren
#

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

thin aurora
#

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).

vale wren
#

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?

thin aurora
#

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.

vale wren
#

thanks!

stark plaza
#

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;
}
gleaming gate
#

For storing item tables and stuff like that, what would be better: Json or Scriptable Objects?

prime sinew
plucky inlet
#

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

gleaming gate
prime sinew
plucky inlet
floral crescent
#

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

somber nacelle
#

are you certain the movement is jittery and not perhaps the camera?