#archived-code-general

1 messages · Page 385 of 1

prime quarry
#

When I download my own repo to see that it works correctly, I always find text mesh pro broken and then i have to reimport it, is there anyway to fix this, this is my gitignore:
.vs/
Temp/
Library/
!ProjectSettings/
!Packages/

swift falcon
#

Why my NAVMESHAGENT doesnt go towars the target?

  1. it rotates towards it
  2. i can see the gizmo in the scene that its trying to walk towards it
  3. but for some reason its not walking.
    is it layer? terrain layer is Terrain
west lotus
#

Native arrays are basically a wrapper around a pointer so I would say no

zealous lagoon
#

Wouldn't it still bypass bound checks?

west lotus
#

Your raw pointer ? Sure I guess but how much speed up is that

maiden heath
#

Do I have to?

#

I want to make an instance of myTile class to be able to be null

#

Without throwing a NullReferenceException

somber nacelle
#

if Tile is a class then it already can be null

#

nullable reference types wasn't enabled by default until .net 6

kindred otter
#

Hey everyone.
In one of my current projects, we have an array to edit values in inspector for a dictionary<enum, float> mapping rarity to some values to apply some stat upgrades. We sorted them by rarity so far, ofc it's errorprone, but a problem for another day. My current "problem" is, when using .ToArray() on some of said dictionaries, can i assume order will be the same as displayed in inspector? In OnEnable the dictionary is cleared and array elements are then added one by one. How could i test this?

leaden ice
#

If you need the order to be preserved, don't use a Dictionary.

#

You can make a struct and just have a List or Array of that struct

warm cosmos
#

how should I silence warnings from plugin code?

#

do i have to modify the script with this issue or are there settings in unity somewhere to ignore warnings from a specific folder, for example

rigid island
#

don't ignore issues, just solve them 🤷‍♂️

#

takes one second to switch it to new function

#

Obsolete: This function is obsolete, use Object.FindObjectsByType instead. This replacement allows you to specify whether to sort the resulting array. FindObjectsOfType() always sorts by InstanceID, so calling FindObjectsByType(FindObjectsSortMode.InstanceID) produces identical results. If you specify not to sort the array, the function runs significantly faster, however, the order of the results can change between calls.

night storm
leaden ice
#

it's in leantween

#

So kinda understandable to want to just mute it

#

We should yell at leantween maintainers though

lean sail
short quiver
#

I'm looking for some direction regarding implementing a game bot behavior. I've implemented Context-based steering, so I can force my bot to go towards some target. However, I'd also like to give the bot directions towards a target, maintaining some distance ~D. The game space is on a horizontal plane, so I essentially want my bot to keep its position on a circle with center C and radius D. How might I modify context-based steering to account for this?
I can probably hack something together, but I imagine this has already been solved, and I do need my solution to be performant.

leaden ice
#

those are necessary folders for the project

wraith cobalt
#

You often need to update the game state much more often than the framerate of the game, especially for physics. You only update the visuals when needed.

warm cosmos
#

Is it best practice to fix plugin code yourself? Idk I feel reluctant to touch stuff - what if there’s a lot of warnings and it’s not a good use of time to sift through it

rigid island
#

not usually but this case would've been okay, but its not big deal since it probably will still work till a few version

#

its up to leantween mantainers to update the actual asset to the new Unity 6 api

kindred otter
rigid island
#

next time. dont crosspost, in a coding channel especially

long ivy
#

k, sry

zealous lagoon
#

Hi, I need help with a design pattern for a bullet hell game. The bullets have a wide range of properties: some rotate, accelerate, stop periodically, change direction randomly, or resize based on distance to the player. I’m struggling with a large, inefficient script to handle all this, especially since I’m limited to using primitives for bullet updates (no classes or inheritance). Any suggestions for a cleaner, more efficient approach?

Ideally it's easy to add any super specific behaviour without clutter...

#

To better explain, my old script had like dozens of parameters to create any behaviour, and the update function was a big unreadable and slow mess.
Like 80% of the function didn't do anything useful as most bullets never used all the super specific behaviour all at once.

rigid island
zealous lagoon
zealous lagoon
#

I can't make classes and have others inherit them.

rigid island
#

uhh is this some type of mod or something ?

zealous lagoon
#

No, as the amount of bullets is quite large, so I'm making everything work in unity jobs. They only allow primitives

rigid island
#

ohhhh okay you're doing DOTS?

zealous lagoon
rigid island
#

hmm Ig you could use interfaces and implement specific behaviors on each?

zealous lagoon
#

interfaces aren't *supported in job structs either

rigid island
#

ah ok I only used small amounts of ECS haven't touched too much n Jobs , maybe someone else knows here 😅

zealous lagoon
#

Yeah it's alright, thanks for taking time to try to help me anyway!

rigid island
#

goodluck! UnityChanSalute

timber finch
zealous lagoon
#

Well I read online you can't use interfaces, I guess I should actually check that before I claim so.

zealous lagoon
timber finch
#

If it’s the C# job system, that falls within the dots purview

zealous lagoon
#

Also seems like interfaces work just fine, whatever forum I read seems to have been wrong

rigid island
#

yeah could've sworn I used them in the past inside a job struct buts its been a while since I touched anything dots

zealous lagoon
#

okay yeah you can store structs that implement interfaces, but you can't store an interface type.

#

I still have no ideas how to do this well

somber nacelle
#

interfaces are reference types which are managed, can't used managed objects in jobs

zealous lagoon
#

yeah okay

#

I think I might have to give up on the multithreading I got working, I just cant figure out any good way to handle this problem. I need my classes UnityChanDown

#

Sorry for spamming the channels so much, this is my last message. Turns out the performance gained by multithreading.. is negligible? I get a 2 fps difference running 1 vs 8 threads... Im out.

short quiver
#

Does Unity provide any tooling for running C# as a script? I just want to test out some of my utility functions

latent latch
#

vs debugger

somber nacelle
short quiver
#

I found what I wanted here

swift falcon
#

is it normal that navmesh stops rotating after reaching its destination? Resulting in some real silly rotations.

rigid island
#

navmesh Agents , rotate on moving yes

short quiver
#

Sorry for spamming the channels so much

proper pier
#

If I have 10 functions that I want to call in a sort of pipeline, is it better practice to nest the calls inside of each function in the order that they will be called, or to have all the functions called from the same function and just pass the variables onto each other from there?

#

so like func1 calls func2 calls func3 vs basePipeLineFunc contains func1, func2, and func3 calls

chilly surge
#

In the first way, func1 is now hard coupled with func2. Eg if you have 2 places where you use Fn (which calls NestedFn1), but now you have a new place where you need to use Fn but want it to call NestedFn2 instead of NestedFn1, you have to make a NewFn that has the exact same code as the old Fn except calling NestedFn2 instead of NestedFn1.

#

This hard coupling doesn't necessarily mean it's bad though, sometimes you do want them to be hard coupled/hidden from public API. So it's situational which one you should go for.

proper pier
#

Yeah I was also thinking second way is better because you can see the whole control flow from one function instead of having to run across 10 files

chilly surge
#

It's situational, not necessarily better.

limber sky
#

what's your preferred way of defining items/abilities/monsters/etc in a JRPG-type game? dictionaries of entities you define at load time with its variables and delegates? different classes that share interfaces that get instantiated when needed? something else?

#

maybe scriptable objects but which reference hard-coded methods that take in parameters stored in said SO? 🤔

short quiver
#

If I have 10 functions that I want to

cosmic rain
short quiver
#

Suppose I have a list of functions List<Func<S, bool>>, and I want to combine them into a single function Func<S, bool> with OR, AND, etc., i.e. is_hungry_and_thirsty = and([is_hungry, is_thirsty])
Is there a C#-native way to combine them, or will I have to make my own wrappers for this? I'm forgetting all of the specific Functional programming lingo

lean sail
limber sky
#

my main worry with SOs is that I'm not sure how to make a neat structure for the delegate methods
tried something before using enums as identifiers that would appear in dropdowns on the SOs, but seemed odd

#

specifically right now I'm thinking about implementing abilities, which are shared by allies and opponents, so it wouldn't make sense for the behavior methods to be part of the prefab

lean sail
lean sail
# limber sky my main worry with SOs is that I'm not sure how to make a neat structure for the...

without seeing how youve defined it, its hard to really say anything. are you talking about the abilities here? what part here are you trying to use delegates for?
also what do you mean by shared abilities? if the ally and enemy can both have the same ability, both ally and enemy can have their own instance of that ability.
the alternative is defining this in code, which really sucks imo,
or trying to serialize a type (or something that you associate to the type like your enum)

limber sky
# lean sail without seeing how youve defined it, its hard to really say anything. are you ta...

by shared I meant that technically every character could learn any ability, so procedurally generated enemies and serialized party members both use lists of references to these abilities
the ability class itself will likely need methods to determine if an ability can be used given the character's state, where the ability can be used on the battle grid, special behavior when the ability is used and/or special behavior when the ability hits each target, etc

#

so essentially... lots of stuff hard-coded called at different moments 😅 not sure if I can parametrize each method or if I should keep it easily editable

lean sail
# limber sky by shared I meant that technically every character could learn any ability, so p...

then yea i could see it being reasonable to not have your abilities be monobehaviours. and yea everything youve described (if an ability can be used, etc) can just be defined on the ability itself, which you likely should be using inheritance for.
im still not really sure which part you're referring to for the "neat structure for the delegate methods". there isnt really much of a structure, when you're given an ability you can just subscribe to everything that the base ability class provides. if you ever lose abilities, unsubscribe. alternatively ditch the delegates entirely, let the ability itself call methods on the characters/vice versa

limber sky
#

in a different project, I had an enum of item IDs, each SO would be assigned the correct unique ID and then a dictionary of behaviors would pair the unique ID with delegates... but it was pretty annoying to manage

lean sail
#

Maybe share an example of what you mean, because to me it just seems very simple in just calling methods when needed here.

short quiver
#

could you not just do `is_hungry(

latent latch
#

Ability + AbilitySO combo

limber sky
# lean sail Maybe share an example of what you mean, because to me it just seems very simple...

for example, a teleport ability- if each ability is its own class inheriting an interface, then once the target cell is selected, I could call the Trigger method from the interface, which would take care of moving the character's position
but instantiating an object is a bit redundant since there's no state change, so a single instance per ability would work... perhaps at load time, a new Ability object is instantiated and the Trigger is a delegate passed as argument
but then all other fields are hard-coded and I'm not sure how to implement that with SOs-

latent latch
#

AbilitySO = read, no touchy
Ability = everything else

limber sky
#

hmm 🤔 so initializer with delegates as above, but other than delegate arguments, it takes in that ability's SO? that could work... if I can make sure no duplicates

latent latch
#

You can stick initializers on the SO too (to instantiate* the Ability prefab) and just pass the SO around instead of referencing some prefab manager

limber sky
#

how do you do that? only way I can think is by using sub-classes inheriting the Ability SO... which isn't so bad if those sub-classes are re-used across multiple abilities otherwise feels a bit tedious

#

also not sure how it'd work out with polymorphism? characters would have a list with Ability SO type so would it work with the sub-class' initializer?

latent latch
arctic ingot
#

Hey hey everyone, so I'm currently dealing with what I believe to be some form of Unity bug (correct me if I'm wrong) where if you disable a parent object with a toggle group and then enable it again, none of the toggles will be on or the default one will be on, but never the last enabled one.

wraith cobalt
# arctic ingot Hey hey everyone, so I'm currently dealing with what I believe to be some form o...

I'd say that it isn't precisely a bug but more a consequence of how it is designed.
Note that the Toggle Group will not enforce its constraint right away if multiple toggles in the group are switched on when the scene is loaded or when the group is instantiated. Only when a new toggle is swicthed on are the others switched off. This means it’s up to you to ensure that only one toggle is switched on from the beginning.

#

The typos in the manual are absolutely bugs though =p

arctic ingot
#

Unless the group is uninstantiated when its parent object is disabled

#

But yeah my problem seems to have nothing to do with that

#

There is also the issue that when anything is selected thats not a toggle, they all disable

severe hazel
#

Hello everyone, I don't understand English well, so I apologize in advance

#

How can I make sure that when I hold down the right mouse button, I can rotate around the character?

sharp lodge
#

Guys do anyone know how can I use github with unity?

thin aurora
sharp lodge
thin aurora
# severe hazel

Keep track of previous mouse position. Rotate based on difference with next frame

#

Also known as "delta"

#

You can also use axis like you have now. If something is wrong then I suggest you explain that

shrewd tendon
#

so basically getting git to work boils down to a .gitignore and git lfs for specific file types

#

git lfs should track .png and .fbx

#

and the .gitignore can be found here:

#

hopefully that helps

#

I'm fairly new to unity too, so I hope this is useful, and I didn't forget to mention something

#

this is also interessting:

#

!vc

tawny elkBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

shrewd tendon
#

What are common patterns you've all used for coding time related things

#

you've got your update function that updates with delta time

#

but you can also use async and await

zealous lagoon
#

Hello, I'm trying to make a ConditionalHide attribute, which I create like this:
[ConditionalHide(nameof(SpawnType), SpawnMde.SIMPLE)]
It works by checking values of enums of certain variables. My problem is accessing the field that I specify, it results in null exceptions in certain nesting situations, like accessing a variable in it's parent.

OnGUI()

ConditionalHideAttribute hideAttribute = (ConditionalHideAttribute)attribute;

// Build the full path to the list property based on the nesting
string fullPath = property.propertyPath.Replace(property.name, hideAttribute.ListFieldName);

// Find the list property using the full path
SerializedProperty variableProperty = property.serializedObject.FindProperty(fullPath); // This is null
quartz folio
#

I see no logic here that would allow you to access a variable "in it's parent", just a dangerous Replace

#

If you want to do something more complex (and robust) you'll have to write a more complex function to maniplate the property path

zealous lagoon
#

I just have no idea how

#

Is there some cool place to read on how these paths work

quartz folio
#

No, just use the debugger or log out the path and take a look

zealous lagoon
#

Alr

#

Ok so when you pass using nameof it only has the name of the variable, which I guess makes sense

#

but I can't find any good way to locate where the field is

#

like is it in the current object, a child, a parent etc.

#

my current method just relied on it being in the current object, but thats not neccessarily always true, which is when I get null

#

ok I dont see any good way to do this, so I guess I just wont use the attribute unless it's in the same object (which sucks but idk how to fix)

zealous flame
#

is jetbens the best ide for coding

spare dome
#

its up to you if you want to use Rider or not, I have no opinion since I have never used it, picking your IDE is personal preference really

zealous flame
#

🙂

sharp lodge
shrewd tendon
#

Git add filename adds a file to tracking

#

Git commit -am “a message saying what you did”

#

That line creates a save point for all added files that have changes

#

Git push -u origin yourbranch

#

This pushes your branch to the remote repo

#

Git checkout yourbranch

#

Picks the branch you will work on

#

Git pull

#

Gets all changes on the branch

#

That is git in a nutshell

spare dome
#

keep in mind this is SLI pushing and pulling, github desktop has an easy GUI for beginners as well

shrewd tendon
#

@sharp lodge One of the hardest things about git is learning how much you can trust it

#

it is very hard to permanently delete stuff if you avoid the -f option

#

and you will at times mess up your repository, and be cursing how to get the thing in order again

#

but it is rare then you'd think, and you'l figure out how te get things in order again with some posts from stack overflow

sharp lodge
#

Look my friend who made the file and he made repository to the game file

#

And now I should make like him and link the game file in my computer
My question is how to do that?? @shrewd tendon

shrewd tendon
#

to get files to your computer you use git pull

#

I have to run now though

#

wife will murder me if I don't

#

and that means I won't be able to finish my game or help you anyway

#

bye

stark stone
#

thats dumb

sharp lodge
#

Or I will just search to git pull

halcyon steppe
#

Hi, i keep having the issue that if i don't use the lookAt function, the camera always looks 90 degrees to the left of whatever i copy the rotation from. Why is this and how to I fix this elegantly without just adding a +90 degree manual offset

leaden ice
halcyon steppe
#

Not really, even if I use cam.forward = player.forward the rotation still is 90 degrees off

mellow sigil
#

Then player.forward is 90 degrees off

thin aurora
#

But even if you don't care about that it's much easier to use since you have a general idea of when something passes time wise

#

And if you don't then turn it into a DateTime

thin aurora
#

Especially when you're a beginner there's little reason to learn all these commands when github desktop is a very easy to use GUI application that does it all for you

sharp lodge
spare dome
#

what

thin aurora
#

I guess you haven't seen their message then

#

Regardless, don't bother learning the commands yet

#

Git has a lot of features, but you don't need any of them apart from the ones that are much easier to use by using Github Desktop

spare dome
halcyon steppe
thin aurora
#

Guido Sales Calvano also gave you bad advice with various steps so that just proves how difficult it can be

spare dome
#

you could use some other git hosting software/website but I do not really use anything else but github desktop, it just works™

mellow sigil
halcyon steppe
#

my player is a bean right now xD I got so frustrated testing that I made a new testing scence

mellow sigil
#

right, the blue arrow is player.forward

vapid pier
#

Hello! Does anyone know of a less expensive or open-source WebGL AR library for Unity?

I'm looking to create a WebGL build with AR functionality, but all the available solutions seem quite expensive. Here are some examples:

Imagine WebAR World Tracker - https://assetstore.unity.com/packages/tools/camera/imagine-webar-world-tracker-248561
ZapWorks Universal AR for Unity - https://zap.works/universal-ar/unity/

ZapWorks works well, but removing their branding costs over $3000. Even with their branding, there’s a subscription fee of $13/month.

I'm also curious about how these plugins are made and would love to learn more about the process.

I am open to suggestions even if there is any other tool through which I can create a physics-based web AR experience, with plane detection

Get the Imagine WebAR - World Tracker package from Imagine Realities and speed up your game development process. Find this & other Camera options on the Unity Asset Store.

Zappar’s computer vision for Unity, JavaScript, ThreeJS and C++.

halcyon steppe
rapid radish
#

Is Unity 6 stable enough for production to be the better choice for a 2D physics game? Removing the splash screen is the main advantage

honest grotto
#

i would say to give it a go, while in developement it will just be battle-tested and if deemed unstable switch(with all game logic and asstets ready should not be such huge undertaking)

rapid radish
honest grotto
#

have not tested further yet so, sorry no intel

rapid radish
#

Anyone using v6 LTS who would give 👍 👎 compared to 2022?

winter valve
#

how 2 make input field interactable? i mean, i have 3d tmp with component input field but when i click on it - nothing happens

knotty sun
hot yacht
#

hy i tried to learn using a Video Player and i want to play a video thats on youtube using URL but i got an error
WindowsVideoMedia error 0xc00d36c4 while reading
after searching its says that its unity editor bug?? is there a way around to fix this error?
https://discussions.unity.com/t/getting-windowsvideomedia-error-0xc00d36b4-on-some-devices/826148/47
unity version : 2022.3.8.f1

    public void SetVideo(string url, VideoPlayer vp)
    {
        videoPlayer = vp;
        videoPlayer.url = "https://www.youtube.com/watch?app=desktop&v=nADTdV8wsXQ";
        videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
        videoPlayer.EnableAudioTrack(0, true);
        videoPlayer.Prepare();
    }
dusk apex
# hot yacht hy i tried to learn using a Video Player and i want to play a video thats on you...

The post stated that the Former Unity Staff member wasn't able to reproduce the error and the error he assumed the OP had was a missing codecs error (Googled the error code). He suggested filing a bug report but never continued responding because likely this may have been an issue on the users end (missing codecs on the users local machine to play the file format)
Are you able to play the video file locally outside of the web browser?

hot yacht
dusk apex
#

What's the file extension of the video?

hot yacht
dusk apex
# hot yacht mp4

I'm not sure but this could be related if you're using Nvidia
https://www.reddit.com/r/WindowsHelp/comments/17gdqae/video_playback_in_some_unity_games_not_working/
Other than that, you can try asking the forums for official support - you may need to provide some system details like hardware spec, operating system, that you're able to play mp4 locally but simply not with the Unity Editor etc
I'm assuming there isn't anything wrong with the code/editor/editor-version and that it's Windows just being annoying

hot yacht
tribal stump
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class PlayerManager : MonoBehaviour


{
    InputManager inputManager;
    CameraManager cameraManager;
    PlayerLocomotion playerLocomotion;

    private void Awake()
    {
        inputManager = GetComponent<InputManager>();
        cameraManager = FindObjectOfType<CameraManager>();
        playerLocomotion = GetComponent<PlayerLocomotion>();
    }

    public void HandleAllInputs()
    {
        inputManager.HandleAllInputs();
    }

    private void FixedUpdate()
    {
        playerLocomotion.HandleAllMovement();
    }

    private void LateUpdate()
    {
        cameraManager.HandleAllCameraMovement();
    }
}

Assets\Scripts\PlayerManager.cs(28,26): error CS1061: 'PlayerLocomotion' does not contain a definition for 'HandleAllMovement' and no accessible extension method 'HandleAllMovement' accepting a first argument of type 'PlayerLocomotion' could be found (are you missing a using directive or an assembly reference?)

Assets\Scripts\PlayerManager.cs(23,22): error CS1061: 'InputManager' does not contain a definition for 'HandleAllInputs' and no accessible extension method 'HandleAllInputs' accepting a first argument of type 'InputManager' could be found (are you missing a using directive or an assembly reference?)
can someone help
everytime i try to fix it i get more errors when i fix those i get these back
like im in a loop

mellow sigil
#

well do those classes contain those methods?

dusk apex
short quiver
#

I have the following switch statement:

(float[] weights, CharacterStrategy[] states) = (perspective.Character.State.Type, perspective.Enemy.State.Type) switch {
  (CharacterStateType.ACTION, CharacterStateType.ACTION) => (new float[]{.8f, .2f}, new CharacterStrategy[]{_strategyDict["Rush"], _strategyDict["Wait"]}),
  _ => throw new System.Exception($"Don't know how to account for {currentStrategy}, {perspective.Character.State.Type}, {perspective.Enemy.State.Type}")
};

Will the compiled code repeatedly reallocate the RHS values? I'd like to use a switch statement here instead of a dictionary because I want to make use of pattern matching, but I'm concerned that this will perform a lot worse because I don't know how else to specify the RHS of the switch cases.

tribal stump
#
using System.Collections.Generic;
using UnityEngine;

public class PlayerLocomotion : MonoBehaviour
{
    public Transform cameraTransform;
    public float movementSpeed = 5f;
    public float rotationSpeed = 10f;

    private Rigidbody rb;

    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    public void HandleMovement(Vector2 input)
    {
        Vector3 moveDirection = (cameraTransform.forward * input.y + cameraTransform.right * input.x).normalized;
        moveDirection.y = 0; // Keep the movement on the XZ plane
        rb.linearVelocity = moveDirection * movementSpeed;
    }

    public void HandleRotation(Vector2 input)
    {
        Vector3 targetDirection = (cameraTransform.forward * input.y + cameraTransform.right * input.x).normalized;
        targetDirection.y = 0;

        if (targetDirection.sqrMagnitude > 0.1f)
        {
            Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }
    }
}
mellow sigil
#

Right, so it doesn't have a method called HandleAllMovement

mossy snow
worldly stirrup
#

https://hastebin.skyra.pw/kixedinaro.pgsql
Problem with movement code: When climbing a slope, the player's speed decreases as it should, but it never reaches zero and goes down the slope, because the code that handles movement based on input is still active and adding to the speed, causing the player's speed to not be zero and making it crawl up the slope

spare dome
worldly stirrup
#

I also have just 3 sizes for slopes, and I want the player to be able to climb them all if they have enough speed

#

Which is the problem I'm facing

#

When climbing up a slope, the speed is never a non zero number because of the code that handles movement based on inputs is still active

spare dome
#

you would just decrease the speed moving up it when on a slope of an angle of your choice until it reaches a certain threshold then turn off inputs and move your character down it

#

this way you get the enough speed and if you do not have it, you will slide down it

#

I would also just make a hard cap for the slope angle as well so a player cannot break your map with movement, unless you want that

worldly stirrup
spare dome
#

you could make it so only above a certain speed can you slow down on a slope as well, you could instead of overriding the inputs, override the velocity make it go in the direction of the slope and make the movement speed lower so inputs do not overpower the slope "force"

worldly stirrup
#

Currently this is the code that handles the slope adjustments, and it runs before running the input code

#
private void accelDecel(ref float speed, float accel, float decel)
    {
        if (Mathf.Abs(speed) < topSpeed || speed * directionHorz < 0)
        {
            speed += directionHorz * (speed * directionHorz >= 0 ? accel : decel);
            if (Mathf.Abs(speed) >= topSpeed)
            {
                speed = Mathf.Sign(speed) * topSpeed;
            }
        }
    }```
#

That is the movement input code

rugged fulcrum
#

hi, I managed to create a grid mesh in a compute shader, however I get these weird black triangles every dispatch seemingly at random. (Black = no normal calculations done, so not processed by the compute shader). Is this just noise from allocating buffers?

short quiver
#

Does C# IEnumerable have any implementation of ArgMax?

proper pier
#

can I not use tex2D in my URP vertex shader? I swear i have before

#

ah it was tex2Dlod

somber nacelle
upper pilot
#
ArgumentNullException: Value cannot be null.
Parameter name: _unity_self

This happens when I start the game while having SO selected in the inspector which contains null properties(in some cases)
Is there a way to avoid that, I can't really set all values to a value so they have to be null sometimes.

#

Actually it seems to happen regardless if anything is assigned in the inspector so that's even more annoying ;_;

solemn ember
#

hello people

#

I ... would like to request to save a file on the players computer from webgl

upper pilot
# leaden ice What's the full stack trace
ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <fe7039efe678478d9c83e73bc6a6566d>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <c91a25f185b743118a39aafa100dff09>:0)
solemn ember
#

type thing, but on webgl

#

where the player can choose the file directory and save it

mellow sigil
solemn ember
#

oh nice, thx

#

and my bad, there's a channel for everything here lol

short quiver
#

Bumping this

solemn ember
#

hey guys, can one access the PlayerPrefs from one project to another?

past raven
#

my rigidbody isnt reacting to linearVelocity

#

nor linearVelocityX and linearVelocityY

#

'''

#
gameObject.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(Joystick.GetComponent<UltimateJoystick>().GetHorizontalAxis() 
* Time.deltaTime * 3f, Joystick.GetComponent<UltimateJoystick>().GetVerticalAxis() * Time.deltaTime * 1.5f);
          ```
rigid island
past raven
#

oh ok

rigid island
# past raven oh ok

did you put this in update? cause rigidbodies should be also moved in FixedUpdate, n always cache your components as well, you should not be calling GetComponent every frame / physics update

past raven
#

THANK YOU

#

it works now

#

omg ive been working on this for so long

#

gives cookie

#

/givecookie

short quiver
#

I introduced a circular dependency into a factory pattern, and I'm really struggling to resolve it:

public class CharacterStrategyFactory {
  Dictionary<string, CharacterStrategy> _strategyDict;

  public CharacterStrategyFactory() {
      _strategyDict = new() {
          {"Rush", new CharacterStrategyRush(this)}, // ...
      };
  }

  public CharacterStrategy Rush { get {return _strategyDict["Rush"];}}
  // ...
}

public class CharacterStrategyRush: CharacterStrategy {
  public CharacterStrategyRush(CharacterStrategyFactory factory): base(factory) {
    _strategyTransitions = new() {
      {CharacterStateType.ACTION, (new float[]{.994f, .005f, .001f}, new CharacterStrategy[]{null, _factory.Wait, _factory.Flee})}, // ...
    };
  }
  // ...
}

The factory points to potential states to return, but the states also point to the factory which is trying to return said states, so the code breaks when it tries to access a value in the factory's dictionary which hasn't finished instantiating. Would it make sense for me to try to lazily evaluate the factory's return states, or should I go about this some other way? I like the idea of asking the state which other states it might transition to (and I do need the potential transitions to be tied to the current state)

summer heart
hot ledge
#

I'm using a mesh generator to create infinite seamless terrain that loads in chunks, the mesh itself lines up perfectly at the seams but the lighting is off. I tried recalculating both normals and tangents.

cosmic rain
hot ledge
worn star
#

are there any open source games being developed in unity

mellow sigil
wispy bolt
#

like i have a question how dose skill trees work and how can i make one like how how dose a skill get activated once some one clicks on it i need to know

#

just like dm me any resources u guys think might be helpful

cold parrot
alpine parcel
#

how do i get to make the transform cords to be in the center of the planet?.
This is the code i use to get the transform of the planet, the planet itself is an empty gameobject with 6 meshes as children and I'm getting the transform of the empty gameobject and get this result of transform center dislocated (I'm trying to explain as best as i can lol)

   {
       gameObject.GetComponent<Rigidbody>().mass = surfaceGravity * radius * radius / gravitationalConstant;
       gameObject.GetComponent<Transform>();
       gameObject.GetComponent<Transform>().localScale = Vector3.one * radius;
   }
mellow sigil
#

Move the children so that the center is where you want it

alpine parcel
#

nah, i just needed to click on the toggle tool handle position and click center to get it centered 😭 , thank you anyway

mellow sigil
#

That doesn't change where the actual center is

alpine parcel
#

you mean that for example, if i scale the object, it scales based on the pivot instead of the "center" right

#

i mean, that is what im getting

#

you are correct

mellow sigil
#

All it changes is where the gizmo is shown in the editor

alpine parcel
#

yh\

#

thank you, it works

hexed pecan
#

How I would solve it is to have an extra row of quads on each side. Now recalculate the normals.
After calculating the normals, remove the triangles for the extra quads. They aren't supposed to be visible, they are just for calculating normals

#

If it doesn't make sense I can try explaining better

swift falcon
#

GUYYYYYS HELP..

  1. can i delete terrain grass (from terrain) via code at some position and then later add it again?
  2. can i (in runtime) get color or texture of terrain at some particular position?
hexed pecan
#

To sample it at a world position, you need to first convert the world pos into alpha map coordinates

#

There's guides on this online, especially if you look for "terrain footstep sound" tutorials and such.

swift falcon
#

ohh

#

thanks

#

what about terrain grass

worldly stirrup
#

so, I fixed my slope problem by making the slopeDown force weaker when you try to brake on it when going down, but now I got a different problem: When the player tries to climb a slope without any starting speed, he gets stuck. It looks awkward and unnatural, so I'm open for suggestions on how to remedy this

hot ledge
#

I'll try that today if I can

vernal jasper
#

So I am creating a game in which the player can change gravity, so sometimes the player will find that the wall in front of them now becomes the floor. However, I am making the game with an isometric view, the camera has right now the rotation (30, -45, 0) and looks like this

However, I am trying to make that when they change gravity to the front wall (for example), they have the exact same view that they have now but in a wall that is rotated -90 degrees in the X axis. I am trying to rotate every way possible the camera but I do not get any result that is similar to the image above when the player is in this wall. Basically, I want to have the same isometric perspective even if they are in the wall but with that wall being now the new floor. Anyone know how I could make something like this?

summer heart
rugged fulcrum
#

damn, what number is this even?

simple egret
vestal arch
vernal jasper
vestal arch
#

nan stands for not-a-number, it's a value used to represent an invalid value, like 0/0, -0/0, sqrt(-1), log(-1)

rugged fulcrum
summer heart
vernal jasper
rugged fulcrum
#

I got a weird problem

#

Basically,it doesnt work in the editor, but it does in renderdoc

rugged fulcrum
#

is it right that mesh.vertices is used when setting MeshCollider.sharedMesh?

short quiver
#

I'm trying to get started with NavMeshes in Unity, and I'm following this documentation, starting with this page, but I'm not able to follow it. It says to "select the scene geometry where you want to add the Navmesh" - what is that referring to? Google isn't turning up anything. I'm assuming this is tied to the "Scene" construct, but clicking on the Scene itself doesn't display anything in the inspector. I then thought that it might be that a given gameobject would contain the specified "Navmesh Surface" component (and maybe its children would contain the obstacles and such), but I don't see "Navmesh Surface" as an option for components. I'm using Unity 6, btw.

short quiver
#

Suppose I have a Prefab that may or may not have a particular component at runtime. In my case, I have Character prefabs that may or may not contain NavMesh Agents. Is there any philosophy around the prefab having the NavMesh Agent component by default, and only enabling it if relevant, vs only creating the component if it's applicable to the agent?

wheat cargo
raven basalt
#

If there are 2 scripts, and both have an on collision method, but one script's on collision method disables the object, and the other scipt/s on collision deals damage, will the damage be able to be done before it is disabled

wheat cargo
native hearth
#

Hey everyone! Looking for some advice. Currently working on a school project. Game is bartending but plays like a diner dash sort of thing. Currently trying to figure out best way to store recipes for the drinks. Was thinking of a scriptable object that stores what ingredients the recipe calls for as well as the amount of each ingredient. (Not designing the drink making to be done in an order, just checking to see if all ingredients and correct amounts are in). Currently looking at scriptable objects for ingredients and recipes just for data storage/checking to make sure user created the drink successfully. I'm trying to find the best way to have an ingredient listed as well as the required amount next to it visible and modifyable in the inspector. Any tips? Screenshot attached is what I have. Was going to turn what I have in the screenshot into a dictionary, but was hoping I could get some tips on best way to proceed. Obviously Dictionarys aren't serializable otherwise I would just do that (ScriptableObject, float). Really want recipes to be fully done in Inspector for ease of use for other members of the team (I'm the only programmer). Thanks!

raven basalt
wheat cargo
wheat cargo
native hearth
#

Not in need of serializing dictionary, really just looking for the best way to store the ingredient and the amount next to it. Is that my best option?

latent latch
#

You can serialize structs

wheat cargo
#

Yeah just make custom data type that contains a field for ingredient and amount, then you can have a list of those

#

You can make a custom property drawer to make it look how you want in editor as well

latent latch
#
public class Drink: ScriptableObject
{
    [Serializable]
    public struct DrinkContent
    {
      public Ingredient Ingredient;
      public int Amount;
    }
    
    public string Name;
    public List<DrinkContent> DrinkContents;
}

public class Ingredient: ScriptableObject
{
    public string Name;
    //Any other info
}```
#

something like that. Can also just make this an SO as well chopped it into SOs

wheat cargo
latent latch
#

Probably an SO if you want to move the instance on the editor besides one place.

native hearth
#

Definitely prefer to do SO. How would that approach work?

latent latch
native hearth
#

Thanks! Gonna take a look

#

Oh that's wonderful! Thank you so much, exactly what I was looking for

short quiver
#

If there are 2 scripts, and both have an

swift falcon
#

hi

fair axle
#

hello

gilded grove
#

Hi

swift falcon
#

hi

fair axle
#

I’ve developed a game for a specific camera aspect ratio, but when I play it on a different phone, it completely messes up the gameplay. What are some possible ways to fix or adjust this? Any advice would be greatly appreciated!

#

sry for using ai to ask me quetion english be shit

fair axle
#

mb mb

#

thank youuuu

plucky lance
#

is there a way to make code where the sprite renderer does a Look at Function and not the whole game object

fair axle
#

i ment the game changes up not the ui

#

ill show you an example

#

i want it in the secound pic to be with like black bars to make sure its the same size

#

the game is not playable on my game

#

i tried using this code

#
    {
        Camera.main.aspect = 16f / 9f;```
#

but its just squish it instead

sleek bough
#

Find a tutorial that explains how to support different resolutions on mobile devices (for fixed 2d view), it's an involved process, you need to design for it.

fair axle
hard sparrow
#

{json} is correct and has all the right values.
Yet the bottom print statement only shows ID is correct, everything else is default. ??
LevelCompletionInfo has a [JsonConstructor] which takes all the values and assigns them. How does this make any sense?

#
    public LevelCompletionInfo(int id, bool heart, bool diamond, bool club, bool spade,
        int wins, int streakWins, int highScore)
    {
        Debug.Log($"creating levelocmpletioninfo. id: {id}, heart?: {heart}, highscore: {highScore}");
        levelID = id;
        heartAchieved = heart;
        diamondAchieved = diamond;
        spadeAchieved = spade;
        clubAchieved = club;
        totalWins = wins;
        winStreak = streakWins;
        highestAmountLeftover = highScore;
    }```
#

once again, only id is correct

#

AH my bad, it's because levelID is a field and the rest are properties. I guess it only can deserialize into fields.

raw badge
#

Hello.
Is it possible to debug a standalone build in the editor?
I am trying to make a mod for a game, of course I don't have the project for it
But I can't seem to figure out how to add (old) UI elements to it, so I'd like to debug the game objects in the editor
Is it possible at all?

cosmic rain
raw badge
#

Yeah, I could get that working

#

But trying to decypher why the ScrollRect refuses to draw it's contents is beyond imesurable pain, if possible at all

#

The problem could be anything at all, as far as I know

cosmic rain
raw badge
#

Is it possible to get the a development standalone build to draw gizmos or Debug.DrawLine?

#

That way at least I could figure out if something is drawing under the UI/mask at 0width, etc

solemn ember
#

need help in #🌐┃web if anyone can take a look at that

short quiver
#

I didn't realize that ScriptableSingleton lives in UnityEditor, and I need some sort of globally accessible Singleton for processing things in my gamestate. How should I go about that instead? I can't use ScriptableSingleton in a build of the game

cosmic rain
fickle tartan
#

can someone help me I im new at code so I don't know what is the issue with my code please help me.

cosmic rain
#

Ah, it's not an SO?

fickle tartan
#

ok thank

raw badge
#

I guess I will do the least bad thing, if anyone got a better idea please tell me

#

hmmm
ScrollRect-> Viewport->Content has a VerticalLayoutGroup yet it's children are not being laid out. I've even ran VerticalLayoutGroup.CalculateLayoutInputVertical(); after they got added to ensure they would get laid out on the frame I queue the print

cosmic rain
raw badge
#

yes, although this code is slight modified to enable manual layout

raw badge
#

After a lot of time, I've managed to get something to draw on screen.
But why does text refuse to draw?
That's how I instantiate a list item. While it works just fine for the Image, the text does not draw at all

umbral obsidian
#

quick question guys

#

@raw badge

raw badge
#

yes? It should draw white

latent latch
#

modifying UGUI in code is a pain

cosmic rain
latent latch
#

is there a reason this isn't all prefab'd

raw badge
#

I don't have the project, I am making a mod through Harmony

latent latch
raw badge
#

Changing from Text to UIText did it. I can finally get somewhere now

vestal arch
raw badge
#

I can't add Image and UIText at the same time on the same gameobject it seems

tacit pewter
#

anyone know if theres a way to change how enums are displayed in editor? these are supposed to say "AmPower" not "Am Power"

#

oop found it! it's the InspectorName attribute

wicked kindle
#

is there a way to instantiate a gameobject into a scene on the root of the scene instead of the child of what spawned it

plucky inlet
wicked kindle
#

lemme double check

#

ok so it doesnt have it as a child but now i need it to spawn where the spawner is

plucky inlet
wicked kindle
#

this is a chat to ask questions but thanks

plucky inlet
#

For sure it is, if you tried things yourself upfront. Reading the docs is the number one thing you should be doing when using a method in unity. Just my advice, to get the best help here if you really need it and how to handle things upfront to solve it yourself. Docs is always the way to go for any development purpose 🙂

wicked kindle
#

definitely, ive been using the docs throught this recent project. This is the first time im coming to the discord for help because these two parts have been giving me trouble and i was running into dead ends. thanks for your small help but not a great way to make a new user feel welcomed.

plucky inlet
#

you will find out while being here for a longer time, but sorry, if it felt too harsh for you

wicked kindle
#

dude its a discord for a game engine, you're acting way to serious.

eager tundra
#

people are spending their time here helping others for free, at least some effort is expected from the other side

thin aurora
plucky inlet
thin aurora
prime lintel
#

Hey all, I want to ask a question about Collider2D OnTriggerEnter2D events.

Let's say I have a script inside of a GameObject that contains the Trigger Collider I am hoping to get an event from. How do I know that when I receive the OnTriggerEnter2D event, it belongs to this specific Trigger Collider I setup in the same GameObject, and not a random one from the scene?

I am still new to Unity so I'm not sure how we link or know which TriggerCollider we are listening to in any script.

thin aurora
#

Alternatively check for a component ont he gameobject that it must implement, or have some sort of metadata on it to check for

#

Kind of depends what you look for specifically

prime lintel
#

Does this mean that I have to call OnTriggerEnter2D from some update function?

quartz folio
#

No. What exactly are you trying to do? Because you have all the info you need in the parameter mentioned

prime lintel
#

I have Collider2Ds setup for every swing of an attack by my character, each attack object contains a small script and a collider.

I want the script to check for collisions when triggered to decrement enemy hp. The colliders and enabled and disabled by another script managing animation events and attack swings

plucky inlet
prime lintel
#

I see so I will only receive this event when the OnTriggerEnter2D is within the same object as the collider?

plucky inlet
#

the ontriggerenter subscribes to your collider set as trigger. When another object enters this collider, it will call this method in your script. The script and the trigger collider of course have to be on the same object, otherwise they wont get the call

prime lintel
#

Okay thanks a bunch!

stuck harness
#

quick question, I want to sort my script in folders with assembly defenitions to make the compiling time faster but when I am trying play I get warnings and my game doesnt work, and then I see that I can search for script in add component and the already added script does not have showing(public) values. Someone know a solution?

cold parrot
prime lintel
#

Hi, I am having trouble with getting my OnTriggerStay2D to return any response. This is how I have things setup, could anyone tell me what I am doing wrong please

public class AttackMelee : MonoBehaviour
{
    public AttackData m_attackData;
    public List<string> m_targetTags;

    private void OnTriggerStay2D(Collider2D collision)
    {
        Debug.Log("Triggered Collision of Attack Collider");
        if (m_targetTags.Find(tag => collision.gameObject.tag == tag) != null)
        {
            collision.GetComponent<Mob>().OnHit(m_attackData.GetDamage());
            Debug.Log("Attack Detected");
        }
    }
}
#

The box collider for Attack1 is enabled and disabled with AnimationEvents elsewhere, I have verified its working correctly

prime lintel
rigid island
prime lintel
#

the gameobject is never disabled. I also checked the activeness of the collider when using the attack, it toggles on and off perfectly when the attack frames come out

rigid island
prime lintel
#

yea

rigid island
# prime lintel yea

I dont really use those dropdowns before, i usually use the old school Physics layer based collision, but your Enemy does seem to have included layers set to "Nothing" maybe it needs the actual Player layer there to enable collision/trigger msgs between the two

prime lintel
#

doesnt seem to make a difference unfortunately 😦

rigid island
prime lintel
#

just tested it, doesnt work either, how do you do it if you dont mind explaining it? I have never done this before so I don't know where to get started haha

rigid island
prime lintel
rigid island
#

functions like Overlaps, Casts

#

far more reliable

prime lintel
#

i see, i was planning on doing that initially but thought it would be hard to visualize the size of attacks, do you use custom gizmos to visualise them?

#

thanks for the help! the debugging steps made it work, seems the issues were with the layers. and rigidbodies were not needed for it to function (unlike what forum posts said)

rigid island
rigid island
prime lintel
#

would that mean the rigidbody of a parent count towards the required collision?

rigid island
gaunt charm
#

Hello! I'm trying to work with a custom track/timeline and most documentation links I find point to nowhere land. I see this discord does not have a channel for timeline/playable/director (there's one for animation, but i'm not doing animation at the moment) so I figure maybe that feature is getting deprecated 😄

rigid island
#

none of those are getting deprecated any time soon

#

playables are quite useful , and sadly the documentation for them is very scarse

gaunt charm
#

I'm looking to do a couple of simple things and cannot figure out how. If you would be so kind to point me in the right direction, I'm trying to:

  • Change the name that appears on a custom playable on the timeline track (Not just when the timeline clip is created, change the TimelineClip.displayName everytime the data inside the playable changes!)
  • Change the color of the clip depending on which PlayableAsset it is
  • Make the duration of a certain type of PlayableAsset fixed (i override duration, but it changes nothing, just the size it has when you create it). As in locking the duration of some PlayableAsset clips on the timeline (making them impossible to resize)
gaunt charm
#

It seems like this feature stood on a lot of "user wisdom" that got lost when various Unity forums and blogs got deprecated too (Now most of the user knowledge I find redirects me straight to a 404 or to Unity Blog homepage). It is unfortunate all that knowledge got binned before anything came to replace it.

rigid island
gaunt charm
#

Unfortunately with its multiple layers of abstraction and great complexity, without documentation and prior knowledge this feature as a whole is barely usable. I come to discord for answers, knowing whatever help you give me will disappear under new messages and somebody will ask the same questions in a month

rigid island
gaunt charm
#

Surely changing the color of a clip based on its PlayableAsset type cannot be this difficult, and I'm just struggling to find the right function to call 🙂

rigid island
gaunt charm
#

ah I mean before watching a whole channel I'm sure since this is the Unity discord somebody must have the answer right?

rigid island
#

yeah but unless you make a thread and hopefully someone stumbles it, it will probably get buried in other help questions

gaunt charm
#

Sorry I thought this was the help channel - where should I create this thread?

#

(Note that my problem is not related to animation, and only related to the scripting API)

rigid island
#

you can create them in discord

#

also, I would probably just use the Unity Discussions page, you are more likely to stumble on Unity employees answering

gaunt charm
#

So I should create a thread in that channel to get an answer ? Under this message for instance

rigid island
#

or just bump your question, within reasonable time inbetween if none answer your question here

gaunt charm
#

I thought thread had to be attached to a message, my bad

#

Simple clip customization on custom track / custom playable

vestal arch
obsidian mulch
#

It’s beautiful seeing these two people interact.
Purple pfp, green name
Green pfp, purple name

rugged fulcrum
#

Hi, i have a question regarding the MeshCollider.sharedMesh property. I procedurally generate my mesh on the GPU via a compute shader, passing it's index and vertex buffers. This works great, however when I try to set a mesh collider for it it detects some nan-values and other goofy values and is thus not able to cook the mesh.

#

The index 17 matches mesh.vertices[17], but not the GraphicsBuffer data from renderdoc

cosmic rain
rugged fulcrum
cosmic rain
rugged fulcrum
lethal dragon
#

hello, i am trying to implement an a* pathfinding algorithm into my 2d platformer game and i just was wondering how i would go about implementing jumping into this algorithm. been searching the internet and couldn't find any meaningful help so came here as a last resort

leaden ice
#

the algorithm itself doesn't change

#

just the structure of your graph

cosmic rain
lethal dragon
#

it has a funcional meaning. i would like to find the optimal points for the player to jump from (change the y coordinate of a custom grid) to get to a specific coordinate faster

leaden ice
#

instead of just walkable neighbors

cosmic rain
#

That might be a bit beyond what an a* can do. Sounds more like a physics calculation. Though I guess you could incorporate it into the algorithm heuristics. It would just be super slow.

leaden ice
#

And properly weighting those edges

lethal dragon
#

okay thanks guys i’ll do some more research on other methods and try to find a solution using a* if not by restructuring my graph

tulip breach
#

How can I convert an x rotation into a y position change?

#

w/o using a parent object

#

im thinking of using the euler thingy and just going from there but is there a built in function for this

leaden ice
#

There are dozens of ways I could imagine that working

hot torrent
#

I have a bunch of textures that i need to slice. Each has a different Cell Size, which i can access during a foreach loop. How do i programmatically slice a Texture? (It's already set to Sprite 2D And Sprite Mode: Multiple).

hot torrent
leaden ice
#

Runtime objects, you can save them as assets if you want with further editor scripting

hot torrent
#

Aa! And how would i do that?

leaden ice
#

With the AssetDatabase class

hot torrent
#

Gotcha!

#

These wouldn't be saved as sub-files of the texture tho, right? Like with manually slicing?

leaden ice
leaden ice
hot torrent
rugged fulcrum
thick terrace
young geyser
#
using UnityEngine;

public class MainMenu : MonoBehaviour
{
    public Animator mainMenuBookHolder;  // Animator for the book UI
    public GameObject canvasInventory;   // Reference to the Canvas that holds the menu

    private bool isMenuOpen = false;     // Track if the menu is open

    void Start()
    {
        canvasInventory.SetActive(false); // Ensure the canvas is hidden initially
    }

    void Update()
    {
        // Listen for Escape key press to toggle menu
        if (Input.GetKeyDown(KeyCode.V))
        {
            if (isMenuOpen)
            {
                CloseMenu();  // Close menu if it's open
            }
            else
            {
                OpenMenu();   // Open menu if it's closed
            }
        }
    }

    // Open menu with animation
    public void OpenMenu()
    {
        canvasInventory.SetActive(true);                 // Show the canvas
        mainMenuBookHolder.SetTrigger("OpenMenu");        // Trigger the "OpenBook" animation
        isMenuOpen = true;
    }

    // Close menu with animation
    public void CloseMenu()
    {
        mainMenuBookHolder.SetTrigger("CloseMenu");       // Trigger the "CloseBook" animation
        isMenuOpen = false;

        StartCoroutine(DisableCanvasAfterAnimation());
    }

    // Disable the canvas after the "CloseBook" animation finishes
    private IEnumerator DisableCanvasAfterAnimation()
    {
        yield return new WaitForSeconds(1f); 
        canvasInventory.SetActive(false);     // Hide the canvas
    }
}```

can someone tell me whats wrong? i have no output errors
#

it s supposedto play an animation when it opened a idle one and another one for closing

clever lagoon
rugged fulcrum
#

I this because there is no density in the mesh? it's just a grid with a heightmap, but i thought that only mattered for convex colliders, i only need a raycast

rustic ember
#

How do I initialize an array of multidimensional arrays? cs bool[,][] arrayOf2DArrays;

#

I tried cs arrayOf2DArrays = new bool[5] as I need 5 2D arrays, but it didn't work. I need the 2D arrays to be of different dimensions

lean sail
rustic ember
lean sail
#

Your inner 2d array should be representing something specific, so making a class containing it will be useful. Then you can also make your own helper functions if needed

rustic ember
#

Right! Thank you 😊

chrome trail
#

How would I go about writing an algorithm to remove unnecessary vertices and triangles from a mesh to try and improve performance? For instance, how would I go about making a general purpose algorithm that takes this mesh from having 8 vertices and 12 triangle points to only having the 4 vertices and 6 triangle points it actually needs?

cosmic rain
cosmic rain
chrome trail
cosmic rain
chrome trail
# cosmic rain Mixed in what sense?

Some of them seem to be more about turning the mesh low poly rather than preserving the same mesh but just getting rid of unnecessary vertices and triangle points

#

And others look, well, really dry. And dense

cosmic rain
#

Dry and dense?

chrome trail
#

I'm not even entirely sure this is what I'm looking for anyway

ivory smelt
#

Hello, does anyone know a good tutorial to make a generic FSM? Been browsing for a while and most of tutorials are either old, not generic at all, or have pretty different approachs.

cosmic rain
chrome trail
chrome trail
cosmic rain
#

The hard part is retriangulation imho.

cosmic rain
chrome trail
cosmic rain
ivory smelt
#

c# has evolved in the last 14 years, some stuff that was done before is now performed more efficiently

cosmic rain
chrome trail
cosmic rain
cosmic rain
cosmic rain
#

It's like trying to build a jet plane by watching a YouTube video.

#

You'll need to look up research papers and sample code

#

The latter one is probably the best approach.

cosmic rain
chrome trail
#

Actually, I'm not entirely sure I have a way to get rid of all redundant vertices

cosmic rain
#

You'll need to use data from the removed vertices to create the new triangles

chrome trail
chrome trail
cosmic rain
#

It doesn't really explain any in detail though.

chrome trail
#

Either way the first order of business is finding a way to identify the vertices that need to be collapsed, right?

cosmic rain
cosmic rain
chrome trail
#

Actually I think I have an idea I might be able to try. I'll read the paper if it doesn't work if you say it's what I'm looking for, though

cosmic rain
#

The idea is simple:

  • find the vertices to remove and remove them
  • retriangulate the mesh

The hard part is how to implement these steps.

plucky lance
#

anyone know where the old "body" section is in the new Cinemachine camera. it used to be called Cinemachinevirtualcmaera

hexed pecan
alpine gust
#

Does anybody know how to make Physics bone?
Like "VRchat","Genshin Impact"

cosmic rain
#

A bone that is affected by physics you mean?

alpine gust
cosmic rain
#

If you have any animations that affect it, the animator would override the position/rotation, so you would need to modify it after the animator updated the bone

alpine gust
cosmic rain
alpine gust
#

noep but I just wanna know
Principle

#

Wait i can make that system just use Collider and rb?

cosmic rain
#

Depends on what you're trying to do.

cosmic rain
tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

alpine gust
#

Thx for help

cosmic rain
#

Though, to be honest I don't think that's a suitable approach for hair. Hair is usually simulated in the shader.

alpine gust
#

Shader?? Ok i need learn shader graph thx

cosmic rain
#

Basically, this is a complex topic with many different approaches. Look up "hair motion in games" for more info.

alpine gust
#

Kk

prime lintel
#

Hi all, may I get some help with events please? I don't know why it isnt invoked despite being subscribed to.

I have a LaserDrone type (derived from Mob type) which contains the m_health member, this member is of type PropertySet

public class PropertySet
{
    public PropertySet(float min, float max, float cur)
    {
        this.min = min; this.max = max; this.cur = cur;
    }

    public float min { get; private set; }
    public float max { get; private set; }
    public float cur { get; private set; }

    public delegate void PassedUpperThresholdHandler(float val);
    public event PassedUpperThresholdHandler OnPassedUpperThreshold;

    public delegate void PassedLowerThresholdHandler(float val);
    public event PassedLowerThresholdHandler OnPassedLowerThreshold;

    public void RaiseEventPassedUpperThreshold(float n)
    {
        OnPassedUpperThreshold?.Invoke(n);
    }

    public void RaiseEventPassedLowerThreshold(float n)
    {
        OnPassedLowerThreshold?.Invoke(n);
    }

    public void Increment(float val)
    {
        var overflow = val + cur - max;
        cur = Mathf.Clamp(val, min, max);
        if (overflow > 0)
            RaiseEventPassedUpperThreshold(overflow);
    }

    public void Decrement(float val)
    {
        cur -= val;
        if (cur < min)
        {
            Debug.Log("Passed Lower Threshold");
            RaiseEventPassedLowerThreshold(min - cur);
        }
    }
}
#

Inside of my Mob definition:

 private void OnEnable()
 {
     m_health.OnPassedLowerThreshold += HandleDeath;
 }

 private void OnDisable()
 {
     m_health.OnPassedLowerThreshold -= HandleDeath;
 }

and

private void HandleDeath(float diff)
{
    //if (!m_alive) return;
    m_alive = false;
    Debug.Log("Mob " + GetInstanceID() + " died");
}
#

Am I doing something wrong here? Why does my event not get invoked?

mellow sigil
#

Add more logs, at least to OnEnable and the RaiseEventPassed methods

prime lintel
#

I have previously added logs there to confirm if they work, they do. It is the Invoke method that doesnt do anything

hexed pendant
prime lintel
#

Each Mob only has one instance of m_health and so far, its the only PropertySet to exist in the type and its derivatives. How do I know if I am subscribing incorrectly? It seems right since I am attaching the death handler to only the m_health event

prime lintel
pine flume
#

Is there a way to move the create scriptable object menu to the top of a right click?

#

Move awesome game to the top

subtle path
#

does anyone know if i can control a sprite resolver label with its array number? the documentation only speaks of strings..... which is totally useless

thick terrace
# pine flume

are you using CreateAssetMenu? it has an order parameter

pine flume
#

I want to move it above the folder option

thick terrace
#

anyway, have you tried the order parameter?

pine flume
#

That doesn't change the order

elder zenith
#

Hello, could anyone advise on how should I make sure the task stops getting executed if the object is destroyed? Currently the task continues to be executed well after the program is stopped

#

I'm guessing something involving a cancellation token?

thin aurora
#

The async-Task pattern goes hand in hand with cancellation tokens for everything, and in this case you'd pass the token into your method and check for IsCancellationRequested. Then when your program stops you want to call Cancel() on the cancellation token source, which in turn delegates this into all of the tokens it created.

thick terrace
# pine flume

it's all relative so you just need to have a lower value than whatever Folder is, i don't know if Unity will tell you exactly but i can say order -9999 definitely puts it at the top haha

thin aurora
#

So if I were you I'd make a global cancellation token source that is cancelled on program end, and you pass this into everything.

#

Note that native .NET methods like Task.Delay and everything else asynchronous also accept this token

thick terrace
#

there's also Application.exitCancellationToken

elder zenith
thin aurora
#

Basically my tip but already implemented, use that instead

elder zenith
#

Hell yeah, thank you both

thick terrace
#

yeah, basically everything you start in unity should at least check the exit cancellation token so things work properly in editor haha

#

switching out of play mode counts as exiting for that token

thin aurora
#

I should have known this was a thing now that there's a proper pattern in Unity with the newest version

toxic fable
#

Hi, is there a Frenchman who knows a lot about unity?

past raven
#

whats a shortcut for a zero vector

vestal arch
past raven
#

ty

thick terrace
thin aurora
#

If it were a class it would save on allocation even, but that doesn't apply here since it's a struct

past raven
#

why arent my rigidbodies colliding

#

my main guy is dynamic and the object is static

#

i have capsule colliders on both

trim schooner
thin aurora
#

Oh, too late

vestal arch
#

are they on layers that can interact?

past raven
#

most of them yea

trim schooner
#

Just go through the link you've been given

past raven
#

why cant unity just fucking work

#

im sick of this shit

#

been working on the same fucking game for 10 years

#

i dont need collision messages

#

i just need them to collide

trim schooner
#

Game dev is complicated
Collisions not working is because the dev set it up wrong

#

Collision messages happen because of collisions.

past raven
#

i dont have the onenter onexit methods in my script

trim schooner
past raven
#

I DONT have those methods

trim schooner
#

JUST FUCKING go through it all, skip that page 😄

#

no wonder you've been working on this for 10 years 😄

golden vessel
#

Hello guys, anyone know any way to increasing the number of layers in unity instead of 32 layer

plucky inlet
rigid island
#

if you need more than 32 something is def wrong in your design

thin aurora
runic kestrel
#

Hello guys ! I'm working on a game with different zones and areas where the lighting of the area will change after "unlocking" it, what's a good way to approach this? Since realtime lights are expensive. Is it possible to use and changes lightmaps for specific areas?

hexed pecan
spare dome
#

you should be moving them via built in rigidbody methods such as LinearVelocity, Addforce, MovePosition (If kinematic), NOT translation as that causes unreliable collisions

past raven
spare dome
#

is this 2D or 3D

past raven
#

2d

spare dome
#

if its 2D check if they are on the same Z axis

#

should be 0 for both the rigidbody and ground (or walls)

leaden ice
rigid island
spare dome
#

Are they?

rigid island
#

thats how I remember it but its been a while

#

gotta test it out again 😛

past raven
robust dome
#

so there are many ways on how to use the new inoput sytsem, what is the easiest and most common way to get the Horizontal or Vertical Axis, we used to use GetAxis("Horizontal"). Thanks in advance.

past raven
rigid island
robust dome
#

ty

rigid island
#

if you create the PlayerInput Input Action asset from the Inpsector component it automatically makes a 2d composite for movement

robust dome
#

yeah i also need to create that actions right, by default there are Move, Fire and Look

rigid island
#

correct

#

SendMessages is the simplest, and then you can later change it if you want to pure events

robust dome
#

ty, i think the new input system is really weird and confusing. takes a lot of effort to find out how it works since there are so many ways

rigid island
#

thats exactly what makes it a bit confusing , you have many options at your disposal

#

but then it turns out its even easier than Input. class , I dont even use it anymore

#

the tricky part is playing around with the button modes

#

eg if you want tap and held

spare dome
#

I have never used dictionaries before, is there any reason to use them over lists or arrays?

rigid island
spare dome
#

what are the main uses of them?

rigid island
#

for example, Dictionaries cannot have duplicates

#

you can only have 1 unique key

vestal arch
#

they're mappings

rigid island
#

they are generally pretty fast as lookup methods

vestal arch
#

they're more akin to a list of tuples than just lists in general
but they're built for key lookup, in terms of api and internal structure

rigid island
#

unlike array is not a fixed size, but unlike list its not an ordered list

hexed pecan
#

Say you want to find an object with a name, from a list. Instead of iterating each object in a list, you can use a dictionary that has the name as the Key and the object as the Value

spare dome
#

sweet

#

just look up the key and it will return whatever value is present?

chilly surge
#

I was going to use the phone book analogy, but realized maybe people nowadays don't know what a phone book is.

rigid island
#

a real life dictionary

#

lookup a definition by word

spare dome
#

so you probably don't want to use dictionaries if you require it to be in a certain order?

rigid island
#

probably not, as dictionaries dont have order

hexed pecan
#

You can always use both though. A list accompanied by a dictionary for fast lookups

spare dome
#

sweet

hexed pecan
#

The dicionary could be generated from the list when needed

knotty sun
#

Or just a SortedList

chilly surge
#

SortedDictionary is also a thing.

vestal arch
#

collections have a few properties that matter outwardly

  • indexed vs keyed vs no random access
  • ordered vs sorted vs unordered
  • exclusive vs nonexclusive
    and a few for performance, like being contiguous, that don't really change the bulk of the api
    unique combinations have unique usecases

for example, lists are indexed and ordered, queues/stacks are ordered, priority queues are sorted, a hashset is exclusive, a dictionary is keyed and exclusive

hexed pecan
#

Oh cool, i never bothered to look into sortedlist

#

Didnt realize it has key/value pairs

vestal arch
#

no a sorted list is just a list but sorted

hexed pecan
#

It implements IDictionary

spare dome
#

I don't have a clue what a queue, stacks, priority queues, or a hashset's are I never used them but I get what you mean

vestal arch
#

ah, bad assumption from other language, sorry.

hexed pecan
#

A list can do everything that queue, hashset or stack can, just with worse performance 😄

vestal arch
vestal arch
hexed pecan
#

Alright but why would you use a worse implementation than what is built into C#?

vestal arch
#

i wouldn't

#

im just not talking about c# specifically

hexed pecan
#

Alright, well I was :P

chilly surge
vestal arch
#

are ring buffers used for stuff other than queues?

leaden ice
#

sure

#

A UI carousel for example

vestal arch
#

thonk not seeing it
isn't a buffer generally for dynamic data?

leaden ice
#

"buffer" is a very broad/generic term just meaning more or less a contiguous array of data.

#

Anyway who says a carousel can't be dynamic?

vestal arch
#

frankly a dynamic carousel sounds like a ux nightmare

leaden ice
#

regardless, a ring buffer would be a good way to represent it in memory.

vestal arch
#

yeah, i was just stuck on what "buffer" really means

#

had a much narrower idea of it

low pecan
#

is there any way to call this reset button in code? I want to set a sprite from a scriptable object then call this reset button to get the collider to match the sprite

naive swallow
#

Or are you expecting this to happen at runtime

rigid island
#

just destroy and AddComponent 😛

leaden ice
low pecan
#

Thank you I didn't realize that was probably just what the button did anyway 👍

leaden ice
#

It's probably not what the button does

rigid island
#

the button calls native C++ code

leaden ice
#

in fact doing this will break any other references you have to the collider

#

so it's a bit janky

low pecan
#

yeah it should work for my usage thank you

fleet gorge
#

addcomponent? does it even calculate the collider for polygoncollider when it gets added?

rigid island
golden vessel
#

Dudes now I want to make an up and down animation for an object and I don't know how to edit the position (update and not to set)

#

Because when I set the position of the 'y' and trying to apply the animation for several objects and putting them in different positions when I apply the animation on them they are go back into the position of my animation!

vernal smelt
#

how come can I click a UnityEngine.UI.Button that's behind an Image/RawImage and how can I fix this?

somber nacelle
#

the image is likely not a raycast target so it doesn't block raycasts

vernal smelt
#

the raycast target box is checked though

somber nacelle
#

well then ask in the proper channel and provide some actual information instead of making people guess

vernal smelt
#

i'm not quite sure what information I can give, I haven't assigned an image, I'm just setting a color so it covers the entire screen, the color is transparent

#

but sure I can try my luck in a different channel

somber nacelle
#

i haven't assigned an image
well that's probably why then

trim schooner
vernal smelt
somber nacelle
#

then i will say this again: ask in the proper channel and provide actual details

#

if you aren't sure what details might be important, then see #854851968446365696 for what to include when asking for help

golden vessel
forest vigil
#

How do I reference my Text Animator TMP?

#

textAnimator = headerText.GetComponent<TextAnimator>(); does not work

somber nacelle
#

you need to use its actual type

forest vigil
#

What do you mean?

somber nacelle
#

i mean you need to use the actual type of the component instead of just guessing what it is, consult the documentation for whatever asset you got it from since it's clearly not your own component

trim schooner
#

if the correct suggestion isn't being displayed when you type that.. then I'd suggest check your IDE is correctly configured

forest vigil
#

The correct suggestion isn't showing up no nothing similar to it at least

somber nacelle
#

what is the asset it came from

#

also you can probably look in your screenshot for a hint as to what you should google

forest vigil
#

The package you mean? The asset isn't mine it's my partner's

somber nacelle
#

the asset as in the asset store asset that this component came from. also simply googling the name of the component was enough to find it. put in some effort.

forest vigil
#

You really love to help don't you

somber nacelle
#

you wouldn't have even had to ask in here if you would have just googled the name of the component. it's the first result

#

here's another fun fact: the type name is also in your screenshot

forest vigil
#

Figured it out

#

see how easy that was

trim schooner
#

do you? 😛

#

Do you know what type is now?

forest vigil
#

Yeah

#

Thanks btw though I'll tell you most people wouldn't like that you'd assume they're trying to get spoonfed

somber nacelle
#

and yet you were so 🤷‍♂️

forest vigil
#

lol

trim schooner
forest vigil
#

Yeah I have it set up, I don't know why it didn't show the suggestion but it worked after I ctrl+Sd my VSC

naive swallow
#

how easy it is to check documentation to find it

somber nacelle
sharp temple
gaunt relic
#
void Update()
    {
        Debug.Log(fallTime);
    // If the velocity is negative
        if (GetComponent<Rigidbody>().velocity.y < -2)
        {
            // Count the time as "fall time"
            fallTime += Time.deltaTime;
        
            // The player "has fallen" I guess
            hasFallen = true;

        }
        // As soon as the velocity is not negative, if the player fell, even a bit
        else if (hasFallen)
        {
            if (fallTime > 5.0 || playerStats.currentHealth <= 0) { // <<< specifically this if
                // put player x y z to respawn pos
                
                // loadScene(DeathScreen)
                SceneManager.LoadScene("Death");
            }

            // If the player has fallen a considerable amount of time
            if (fallTime > 1)
            {
            // Hurt the player based on how long they fell
                playerStats.currentHealth -= fallTime * 25;
            }

            // Reset fall measurements
            hasFallen = false;
            fallTime = 0;
        }
    }

does anyone know why when falltime > 5, the if condition doesn't work?

gaunt relic
#

if (fallTime > 5.0 || playerStats.currentHealth <= 0) { // <<< specifically this if

leaden ice
#

There are twoi other conditions required there

#

hasFallen has to be true, and ccurrentHealth has to be less than 0

gaunt relic
#

and?

#

is that not or?

leaden ice
#

and.. if they're not both also true

#

oh

#

yes sorry

#

you do need hasFallen to be true though

gaunt relic
#

hasfallen should theoretically be true since I am getting a debug log from the first line

leaden ice
#

the first line logs no matter what

gaunt relic
#

and fallTime += Time.deltaTime; is adding

leaden ice
#

it's the first line in Update

#

It looks to me like you're setting hasFallen = true immediately when the object first starts falling.

That means next frame you will run the else if which does fallTime = 0 at the end

#

so fallTime will only ever be Time.deltaTime at most

#

one frame worth

#

I don't see how fallTime could ever be more than 5

#

unelss you had a single frame that lasted more than 5 seconds

#
            // Reset fall measurements
            hasFallen = false;
            fallTime = 0;```
#

^ This is screwing you up

#

it doesn't make sense

gaunt relic
#

I see your point, but when I remove fallTime> 5.0 that condition and just take damage instead of falling indefinitely, the scene loads

#

meaning hasFallen is true constantly when falling

leaden ice
#

instead of sluething around like sherlock holmes why not attach a debugger or add more logging so you can know for sure

#

Here's what is definitely true:

  • If statements work properly, 100% of the time
fleet fern
#

Currently working on making editor tools, and trying to display a UnityEvent property in a custom inspector, so that way a designer can assign unity events to a "story beat system"
I know that you can use PropertyFields to read SerializedProperties, but since the UnityEvent is being retrieved from a list of custom classes that don't derive from UnityEngine.Object, they can't be read
Is there another way to do this, or is that not possible within the constraints of the editor?

naive swallow
leaden ice
#

You mean you just have a List<object> or something>

#

You can always do:

if (theProperty is UnityEngine.Object uobj) {
  EditorGui.DrawPropertyField(... uobj );
}```
#

er, that's a bit off

#

since you need a SerializedProperty

#

but yeah

fleet fern
#

Essentially, there's a custom class "StoryBeat" containing a list of "StoryBeatEvent"s, each with their own UnityEvent Event

leaden ice
#

Is StoryBeatEvent serializable?

fleet fern
#

yes

leaden ice
#

So... it should work out of the box unless I'm missing something

#

What type is the custom inspector for?

fleet fern
#

when making a SerializedProperty, you start with a SerializedObject to pull the property from, right?

fleet fern
leaden ice
#

A custom editor can only be made for a type that derives from UnityEngine.Object

#

i.e. a MonoBehaviour

#

or a ScriptableObject

#

you said youre writing a custom inspector

#

unless I misread somewhere

fleet fern
#

and those can't be read by SerializedObject, since they don't derive from Object

leaden ice
#

sure - so the SerializedObject is the MonoBehaviour

#

the field of type StoryBeatEvent would be the SerializedProperty

#

and within that SerializedProperty the event would be another SerializedProperty

fleet fern
leaden ice
#

e.g.

SerializedObject sobj = new SerializedObject(myMonoBehaviour);
SerializedProperty eventProperty = sobj.FindProperty("someEvent");
SerializedProperty unityEventProperty = eventProperty.FindPropertyRelative("theUnityEventField");```
leaden ice
#

It seems unlikely "UnityEvent" is the name of the field

fleet fern
#

yeah, I can draw something up

fleet fern
fleet fern
leaden ice
#

Are both StoryBeat and StoryBeatEvent marked with [Serializable]?

#

and are those fields public, or marked with [SerializeField]

fleet fern
#

yes, the classes are serializable, with the fields public

river cave
leaden ice
# fleet fern yes, the classes are serializable, with the fields public

you should be able to do e.g.:

SerializedObject serializedStoryManager = new SerializedObject(myStoryManager);
SerializedProperty storyBeatsProp = serializedStoryManager .FindProperty("StoryBeats");

for (int i = 0; i < storyBeatsProp.arraySize; i++) {
  SerializedProperty beatProp = storyBeatsProp.GetArrayElementAtIndex(i);
  SerializedProperty beatEventsProp = beatProp.FindPropertyRelative("StoryBeatEvents");
  for (int j = 0; j < beatEventsProp.arraySize; j++) {
    SerializedProperty sbeProp = beatEventsProp.GetArrayElementAtIndex(j);
    SerializedProperty eventToRunProp = sbeProp.FindPropertyRelative("EventToRun");
    EditorGUILayour.PropertyField(eventToRunProp); // for example
  }
}```
#

it's pretty laborious with the lists

fleet fern
#

I'll go ahead and start adapting/implementing something like this and see if it works

#

does it actually need the eventObject.ApplyModifiedProperties(); line in there, like from the source I found, or was that something not as necessary?

fleet fern
hard sparrow
#

So I've almost got this save system working, just one problem.

            JsonConvert.DeserializeObject<PlayerData>(File.ReadAllText($"{_playerDataDirectory}{_slash}{PlayerDataFileName}.json"));```
This gives an error because one of the data is List<Condition> where Condition is an abstract class. The error: ```JsonSerializationException: Could not create an instance of type Condition. Type is an interface or abstract class and cannot be instantiated.```
I don't even know why it's trying to instatiate, PlayerData is a regular C# class
vagrant blade
#

!ban 980901204597030912 spam/racism

tawny elkBOT
#

dynoSuccess friedreports was banned.

hard sparrow
#

Actually in this case I guess it's simple to make Condition a non abstract class. But still, don't know why it does this

mellow sigil
#

Instantiate in this context doesn't mean UnityEngine.Instantiate, it means creating a new instance of a C# class with new

#

The problem with abstract classes is that when you serialize the data into JSON it doesn't contain information about what the actual class is. So when deserializing it, it's not possible for it to know what class to use

#

It doesn't even need to be abstract, if you have List<A> then it will deserialize all the data into instances of A regardless of what type the original data is

sage spire
#

Hi can anyone help me here Im new to Unity

somber nacelle
sage spire
#

I dont get why it says it couldnt be found

knotty sun
somber nacelle
tawny elkBOT
hard sparrow
#

I guess you need to do some kind of ID lookup instead, where you just serialize IDs?

#

In this case, Condition is also a scriptableobject, so I can maybe just serialize the GUID?

sage spire
mellow sigil
naive swallow
sage spire
hard sparrow
#

I thought they were at least stable within a game instance (a player's copy of the game). But I guess even then it would caue problems if someone uninstalled the game and reinstalled it later

naive swallow
#

What's a Rigi body

sage spire
#

huh

sage spire
#

or u mean the dot?

naive swallow
hard sparrow
#

So how the heck are you supposed to save this data...?

naive swallow
#

Is it a script you've made? Maybe show the code for Rigibody2D

sage spire
#

omg

#

I meant to type Rigid

spare dome
#

configure your ide

sage spire
#

@naive swallow

naive swallow
# sage spire

Well, yeah. You can't add a vector to a Rigidbody, that wouldn't make any sense

sage spire
#

But that is what the tutorial showed me to do

naive swallow
#

Show the tutorial

sage spire
#

Let me rewatcg just in case

sage spire
#

Getting a character to move in your Unity game engine takes some understandment. In this tutorial you will learn how the New Input System works and how you use it to move a 2D character. By combining a Sprite Renderer and a Rigidbody2D we will make moving as simple as possible. This tutorial is focused to be beginner-friendly and explains all th...

▶ Play video
#

Minute 11:28

spare dome
#

rb.position

#

that is a vector, you are just giving it the raw body

naive swallow
# sage spire https://www.youtube.com/watch?v=xrLlZ1mHCTA&t=176s
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 181
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-11-12
sage spire
#

im sorry for wasting all of u guys time

spare dome
#

I'm wondering who would do that

naive swallow
sage spire
#

it moves bobaparrot

#

thx a lot

candid herald
#

hmm i have a strange unity IAP issue, that someone else complained about in july but didn't ever post a resolution to. in editor, i can connect to the IAP initialization in editor fine, but when i build to android and try to load the game there, i get a failure response to UnityPurchasing.Initialize OnInitializeFailed InitializationFailureReason:No product returned from the store. error

lunar acorn
#

Chat GPT is telling me to bind the rightclick under hold... I feel like thats wrong but i dont see anywhere to bind what button im actually pressing. Help?

rigid island
#

learn how to properly use the Input System

#

mouse delta isn't for button, it gets the value between the 2 moved points

lunar acorn
#

I just want help. I dont understand how to set it and i went to chatgpt becasue i couldnt find a straight answer. Are you able to help?

#

This is what it said:

hasty dove
#

i posted this in art but bc it has code i figured someone could help

Hey can someone help me as to why the animation of the slashing isnt flipping as intended on the left side when the player faces left.

private void Attack() {
myAnimator.SetTrigger("Attack");
weaponCollider.gameObject.SetActive(true);

    slashAnim = Instantiate(slashAnimPrefab, slashAnimSpawnPoint.position, Quaternion.identity);
    slashAnim.transform.parent = this.transform.parent;
}

public void SwingUpFlipAnimEvent() {
slashAnim.gameObject.transform.rotation = Quaternion.Euler(-180, 0, 0);

    if (playerController.FacingLeft) { 
        slashAnim.GetComponent<SpriteRenderer>().flipX = true;
    }
}

public void SwingDownFlipAnimEvent() {
    slashAnim.gameObject.transform.rotation = Quaternion.Euler(0, 0, 0);

    if (playerController.FacingLeft)
    {
        slashAnim.GetComponent<SpriteRenderer>().flipX = true;
    }
}

is there something wrong with my code? I cant seem to see a reason as to why it isnt working

neat mirage
#

does anyone get this file auto generated by unity? must i gitignore it or is there a way to stop it from genning

wide terrace
hasty dove
reef garnet
#

Anyone here experienced with mesh generation? I need help setting UV's for a procedurally generated mesh.

I need to make sure every yellow point within the blue octagon is on a single UV texture 0,0 to 1,1

#

Part 1

int pointOffset = verts.Count;
List<JunctionEdge> edges = intersection.GetEdges().ToList();
List<Vector3> intersectPoints = new List<Vector3>();
List<Vector3> curvePoints = new List<Vector3>();

for (int j = 0; j < edges.Count; j++)
{
    int next = j == edges.Count - 1 ? 0 : j + 1;
    int previous = j == 0 ? edges.Count - 1 : j - 1;

    JunctionEdge currentEdge = edges[j];
    JunctionEdge nextEdge = edges[next];
    JunctionEdge previousEdge = edges[previous];

    Vector3 leftIntersect = FiveBabbittGames.MathUtils.GetIntersectionPoint(currentEdge.left, currentEdge.direction, nextEdge.right, nextEdge.direction);
    Vector3 rightIntersect = FiveBabbittGames.MathUtils.GetIntersectionPoint(currentEdge.right, currentEdge.direction, previousEdge.left, previousEdge.direction);
    Vector3 currentEdgeLeft = currentEdge.left;
    Vector3 nextEdgeRight = (j < edges.Count) ? nextEdge.right : edges[0].right;

    BezierCurve curve = new(currentEdgeLeft, leftIntersect, nextEdgeRight);

    intersectPoints.Add(leftIntersect);
    curvePoints.Add(currentEdgeLeft);

    // Quad Verts
    verts.Add(currentEdge.left);
    verts.Add(leftIntersect);
    verts.Add(rightIntersect);
    verts.Add(currentEdge.right);

    // Curve Verts
    float curveStep = 1f / (float)curveDivisions;

    for (float t = curveStep; t <= 1f; t += curveStep)
    {
        Vector3 pos = CurveUtility.EvaluatePosition(curve, t);
        curvePoints.Add(pos);
        verts.Add(pos);
    }

    int triOffset = pointOffset + (j * (4 + curveDivisions));

    ```
#

Part 2

// Quad Tris
    // Top Left Triangle
    tris.Add(triOffset + 0);
    tris.Add(triOffset + 1);
    tris.Add(triOffset + 2);

    // Bottom Right Triangle
    tris.Add(triOffset + 0);
    tris.Add(triOffset + 2);
    tris.Add(triOffset + 3);

    // Curve Tris
    for (int k = 0; k < curveDivisions; k++)
    {
        int current = 4 + k;

        if (k == 0)
            tris.Add(triOffset + 0);
        else
            tris.Add(triOffset + (current - 1));

        tris.Add(triOffset + current);
        tris.Add(triOffset + 1);
    }
    
    // THIS IS PLACEHOLDER CODE FOR THE UV's
    // Quad UVs
    uvs.Add(new Vector2(0, 0));
    uvs.Add(new Vector2(0, 1));
    uvs.Add(new Vector2(1, 1));
    uvs.Add(new Vector2(1, 0));

    // Curve UVs
}```
leaden ice
reef garnet
#

Second this, we don't have ChatGPT's context

fleet gorge
#

its better to ask your question here than ask chatgpt because chatgpt will set you in the wrong direction and that would make it more difficult for us to help you

reef garnet
#

I have a hypothesis but now I need to know how to get the bounds from a list of vertex positions, anyone know how to do that?

leaden ice
#

DO you mean a convex hull? Concave Hull? Or an AABB?

fleet gorge
#

the bounds from a list of vertex positions? you can start working with each axis, loop through the list, find the minimum X, maximum X, minimum Y, maximum Y, etc

#

this will give you the box bounds of the vertices

reef garnet
#

a square that contains every point that I can easily translate the positions coordinates to be between 0 and 1

reef garnet
leaden ice
reef garnet
#

ooooh

leaden ice
#

at the end b will perfectly encapsulate all the vertices in a minimal AABB

fleet gorge
#

i learn something new every day

leaden ice
#

oh wait sorry Encapsulate doesn't return anything

#

it's just b.Encapsulate(vertex); without the b = bit

hasty dove
#

Can someone help me with a issue? ~

Im trying to code a simple toggle that when the player presses "G" it turns off the sword object (putting it away) but I seem to only be able to get it to turn off and nothing i do seems to be able to re enable the sword object

#
private void Update()
    {
        MouseFollowWithOffset();

        if (Input.GetKeyDown(KeyCode.G))
        {
            ToggleSword();
        }
    }

private void ToggleSword()
    {
        gameObject.SetActive(!gameObject.activeSelf);
    }
lean sail
tawny elkBOT
hasty dove
leaden ice
#

restructure your hierarchy as needed to make that happen

hasty dove
#

Oh i see, its not working because the code cant run if the object is off? If i put that in my controller file itll be okay?

leaden ice
#

not sure what a "controller file is"

hasty dove
#

Player Controller sorry

leaden ice
#

but yes, if you disable a different object than the one this script is on, this script can continue running

hasty dove
#

Awesome thankyou sorry for the stupid question

cursive moth
#

Hey, I am trying to load a config from a JSON file.
I managed to get the file to actually load, which can be seen in the inspector shown in the very first picture I attached.
Issue is, values for some reason don't get set to ones from the JSON file.
Is this possibly because the JSON is unable to assign values to Properties?
If yes, is there a quick and easy workaround or will I have to literally have double fields just to accommodate to the Unity's JSON loader?
Here's a class JSON is supposed to load to: https://github.com/nnra6864/Nisualizer/blob/master/Nisualizer/Assets/Scripts/Config/Config.cs
And here's the JSON loader script: https://github.com/nnra6864/Nisualizer/blob/master/Nisualizer/Assets/Scripts/Config/ConfigScript.cs
Thanks in advance!

cursive moth
#

please @ me if you are able to help

oblique wave
#

does anyone know if you can execute code to an asset when imported

#

ie, when importing an FBX run code to change a name on its animation clips

leaden ice
#

You just have to follow those rules

#

It's not clear which things you're expecting to be serialized or not here

#

The only things you actually have serialized in your class seem to be those "default" fields

digital summit
#

Hello! Fairly new to Unity here but experienced in C#! Im trying to create a game that will have a lot of item classes and sub-classes that will also havr a sub-class and in that class the values for the item. I want to make it as modular as possible, meaning I want to be able to change items names and values really easy and fast. I tried using ScriptableObject for every item but trying to add too many items, might take a while to set them up and imagine wanting to change or add a value for all of them... I also had the idea of using a XML or JSON file but havent implemented that yet. So any ideas how I should do it?

#

Please @ or DM me if you want to help. Thanks!

lean sail
latent latch
#

Not to mention how easier it is to reference with an SO compared to explicit pathing/IDing if these items are anything but trivial

cursive moth
cursive moth
# cursive moth Ah, so I literally have to mark it as `[SerializeField]`, in order for it to wor...

Since this is the case, would it be an uncommon/bad approach to have an additional abstraction layer, which is literally just a Config class that only gets the JSON data loaded into it, and then the current class I have is just a place that would then store all that data into actual properties so you can have stuff like OnValueChanged etc.?
I genuinely can't think of another way to work around this, but then again, I can't say I have a lot of experience w JSON in the first place tbh.

#

Yes, it's p much code duplication, but I am out of ideas...

plucky inlet