#archived-code-general

1 messages · Page 156 of 1

fleet shell
#

To my knowledge each vertice should have it's own. From my understanding of it all it should ust apply the image of the noise over the top as if it were a 2D image, with the dimensions of the noise map matching that of the mesh. But just seems to stick to one grey unless I adjust the scale

rotund burrow
#

How to start with visuals? What are shaders, lightning, textures, material maps and so on? I need a deep dive tutorial. The question is in #✨┃vfx-and-particles

hard estuary
# fleet shell To my knowledge each vertice should have it's own. From my understanding of it a...

If the UVs are set correctly, then it should stretch the image properly. You can easily check if it's the problem with the mesh by using a material that works correctly on some basic meshes like Quad or Cube. If the material behaves differently, then the problem lies on the mesh side.

What do you mean by "seems to stick to one grey unless I adjust the scale"? Does it turn to a different shade of gray when you generate the noise differently?

fleet shell
#

Correct, if you generate a new noise, the grey will shift to a different colour/shade, suggesting that it is reading the noise map, just not applying the texture properly

hard estuary
swift falcon
#

Hello. I'm creating a gameobject from scratch (in code) and assigning a spriterenderer component to it. I want to load an individual sprite from an atlas with multiple sprites directly from my assets folder. I've come as far as doing renderer.sprite = Resources.Load<Sprite>("Assets/Texture2D/buildings.png"); but I have no clue on how to load a sprite from an atlas.

simple egret
#

First things first, that's not how the path works in Resources.Load! It should not have an extension, and will search in all Resources folders it finds

swift falcon
#

oh thanks

#

so thats one future problem solved, but how do i go about getting individual sprites from an atlas?

primal wind
#

What kind of atlas? One made in Unity or a single image with all your spitres on it?

#

For the first case i think you can do that in editor and in code but the other case its purely UVs

fleet shell
# hard estuary Could you `Debug.Log` uv of each vertice?

UVs seem all good. Applying the noise texture to a cube works just fine, just doesn't apply to the plane correctly which leads me to believe the issue is centralised within my MapDisplay script, but for the life of me can't figure out where

hard estuary
swift falcon
craggy cedar
#

When I try to debug in Unity 2021.3.3f1 with Visual Studio, the first time it attaches correctly, but the next times I get a "No connection could be made because the target machine actively refused it" error
this started happening today

fleet shell
#

Now time to properly generate the maps to get terrain why_god_why

gray mural
#

How do I make my game to remember user?

#

how do I make is so that users already has their account loaded without need to connect to database by typing name or email?

rigid island
gray mural
rigid island
gray mural
rigid island
#

if you're using unity authentication then it already stores token iirc

gray mural
rigid island
#

so why did you send unity authentication docs

#

you have to make your own session cookies then

gray mural
#

as you have written

rigid island
#

well yeah it's a common practice in already established systems

gray mural
rigid island
#

otherwise you have to make your own token system

#

welcome to authentication hell..

#

it's very annoying

#

that's why third party solutions exists

gray mural
#

I just want user to register in my game, then when they quit game and open it, they are already loaded

rigid island
rigid island
gray mural
gray mural
#

I have to store user in database

#

or do I just do both?

#

playerprefs & sql?

rigid island
#

that's how unity does it

#

You store user in DB. You store their token (logged in authenticated info)

#

in playerprefs

gray mural
#

when they load the game one more time *

rigid island
#

that means they have logged in already

#

but you need to put a refresh token ideally and timelimit

gray mural
rigid island
gray mural
#

🤔

rigid island
#

did you lookup what a token is?

gray mural
gray mural
rigid island
#

when you login user you store their token in playerprefs..

gray mural
rigid island
#

if playerprefs has token, that means they logged in

gray mural
#

my bad

gray mural
rigid island
#

yes playerprefs is typically in the local pc registry

#

thats why its bad for permanent saves

gray mural
rigid island
#

ofc every SDK i've seen so far with unity does it

#

unity themselves does it, read the docs

gray mural
#

ok, it seems pretty easy to implement

rigid island
gray mural
#

nice

#

thank you for your help 🫡 @rigid island

weary stirrup
#

So I got some issues with this funny stickman game absicly what im trying to do is have the stickman grab a weapon and have the weapon rotate the same way as the lower arm while still being affected by physics. I tried achieving this by making rigidbody2d Kinematic than making a FixedJoint2D and setting isKinematic to false right after. It works fine but after a few seconds of playing around with the sword it suddenly glitches out and starts flying across the screen. here is code: https://paste.myst.rs/ti3avdp4

crude iron
#

Does anyone have experience with Gradle? Im having some issues with it and I have zero knowledge on how to fix it. I recently updated from Unity 2020.*.* to Unity 2022.3.5f1 and along with that it cause my outdated version of gradle to stop working. So I downloaded the most recent version of gradle and it still doesnt work. Would someone be able to help me? Ill include console logs and everything

#

104,610 people

gray mural
crude iron
#

You can look it up in the community servers tab

gray mural
raven orbit
#

is there a way to do something like this? Basically making a max distance that a camera could zoom to, the camera is on an angle so it seems much more tricky than if it was not angles at all

devout harness
#

You can multiply the localPosition by a scalar, i.e. 2.5 / localPosition.magnitude

#

That'll achieve the same effect

raven orbit
#

This is basically how I am moving it

#

not sure exactly what you mean when you say scalar

devout harness
#

Scalar meaning a single number which scales the length of the vector

#

So someVector * 0.5f would produce a vector that is half as long

raven orbit
#

I don't understand the application

devout harness
#

Assigning the magnitude to 2.5 would be equivalent to normalizing the vector then multiplying it by 2.5

#

(Normalizing the vector makes its length ((the magnitude)) 1)

simple egret
#

You can use Vector3.ClampMagnitude() for that, if you don't want the magnitude to go past a certain value

#

vec = Vector3.ClampMagnitude(vec, 2.5f)

raven orbit
#

I was thinking of using a min/max clamp but I'mw not sure where to set it

gray mural
#

hello

#

How do i call user's profile picture?

#

avatar ?

#

question to people who are confident in their English

raven orbit
#

Avatar, Character Icon, Player Picture

devout harness
#

Profile picture works universally for the picture, avatar can apply to your character in a game

gray mural
gray mural
raven orbit
#

Avatar is a mostly incorrect word for it but people do use it

gray mural
#

I see

#

I gonna use picture then

#

thank you both

leaden solstice
#

"pfp"

raven orbit
#

Character Widget and Player Icon are ones I hear often at work

gray mural
#

hello one more time, is @gray mural a nickname and unique one an username?

#

I need it for my db

leaden solstice
#

Unique user id would look like 1025482839954821222

simple egret
#

Your DB should have a primary key, which is an integer on 32 or 64 bits or longer

gray mural
leaden solstice
gray mural
#

or user id?

simple egret
#

Username

gray mural
#

name that is unique I think

simple egret
#

Your user ID is 1025482839954821222

gray mural
simple egret
#

Right click, copy user ID

#

Might need to enable dev mode

leaden solstice
#

You need to turn on option yeah

gray mural
#

356398888036335617

#

but both id and username are unique?

simple egret
#

Discord ensures there are no duplicate names, but usernames and IDs have different functions

gray mural
#

also email is unique 🤔

tawny mountain
#

Does anyone have a good tutorial on setting up a mobile joystick ui

simple egret
#

You can add a UNIQUE constraint on your DB column if you need to have unique usernames

gray mural
#

thank you both

tawny mountain
#

No interested in downloading an asset , I'd like to build it myself

gray mural
#

I should just implement player account scene and have to know how to call things correctly, not uniqueName and name

simple egret
#

And probably an index, clustered if available, on that username column, so searching for a name is fast!

simple egret
#

Database index, speeds up fetching of rows by one of its columns by either physically sorting the values on disk (clustered index), or using some hash table (regular index)

simple egret
#

If you do a lot of searches by username WHERE username = 'something', then you probably want an index on username

gray mural
simple egret
#

Depends on which database management system you're using. It might not be available on all of them

gray mural
#

SQLite

simple egret
#

Hm, it's a file so probably not available.
Googling "sqlite add index" should yield some results

gray mural
simple egret
#

Oh that's available, but there's no clustered index as it's using a special column rowid to physically order the row

#

But yes, you can use indices on sqlite

gray mural
glossy wave
#

I have a NullReferenceException problem when trying to get the parent gameobject of a gameobject my player is looking at

#

"Object reference not set to an instance of an object"
on this line:

heldObjectsOriginalParent = lookObject.transform.parent.gameObject;
simple egret
#

Either lookObject is null, or it doesn't have a parent

nova crystal
#

anyone know how to paint trees on unitys built in terrain using code ?

glossy wave
simple egret
#

Just now, or before you got the error?

glossy wave
#

just now. this is my code rn:

        if (lookObject != null && lookObject.transform.parent.gameObject != null) heldObjectsOriginalParent = lookObject.transform.parent.gameObject;
#

neither the object or its parents can be null

lucid valley
#

lookObject.transform.parent can still throw doing the .gameobject afterwards

simple egret
#

Yeah your if statement is flawed on that second condition

lucid valley
#

your check should be lookObject.transform.parent != null

glossy wave
#

oh, that works! ty!

languid hound
#

How should I go around doing this

        public void TryFindValidInstance(AnyMonoBehaviour gameObjectType)
        {
            if (FindObjectOfType<AnyMonoBehaviour>())
            {
                return AnyMonoBehaviour;
            }
        }
languid hound
#

Yeah but to make it so there aren't 10 billion ugly if statements and I can do some other stuff if there isn't an instance I wanted to turn it into a function

#

You pass in a MonoBehaviour class for example a GameManager script

#

And it'll try to find an instance with FindObjectOfType and return it

#

If there isn't one then do other stuff

leaden solstice
languid hound
#

Yeah

leaden solstice
#

Try to avoid Find functions tho, prefer DI solution, but singleton if inevitable.

leaden solstice
languid hound
#

Alr

#

Cheers

halcyon venture
#
float fillPercent = XP / maxXP;
Debug.Log(fillPercent);

i only get zeros. its an xp system and i am making a bar. if the xp is 10 and max is 100 it should output 0.1. but its giving zero.

#

nm

#

nvm

#

i needed to add (float)

azure saffron
#

Is there any way to get a summary of all profiling results in the unity profiler rather than inspecting frame-by-frame? I want to see across all recorded frames, which of my script methods took up the most cpu time.

#

Ideally also across all threads

unreal sonnet
#

Hey there, not sure if this is the right place to ask this but I'm looking for someone who could help me out with a script (I am willing to pay for it). DM me for more info about the project in case you are interested, cheers

tawny elkBOT
unreal sonnet
#

aw i see, thanks

wild bane
#

Does Physics.IgnoreCollision overrides the layer collision matrix?

fluid willow
#

Okay, ill give some background first. So for awhile i have been trying to start work on a cloud shader and i have been having problems figuring out how i can implement 4D Worley noise in a comprehensive way, either in a shader script or in a regular C# script. I have attempted to search for answers both on unity forums and other various threads/forums. The whole point of this part is that i want to be able to animate the clouds growing using 3d noise and i figured that using 4D noise will make the animation better. If there is any documentation or threads on this subject that i could use that would be great!

sage kite
#

Anyone familiar with unity and VR game development? I got this problem where I want to make use of natural walking and go through a portal, but it dosent seem to work unless I use the joystick to my VR headset, but when I physically go through the portal the portal dosent work

icy geyser
#

!learn

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

river sentinel
#

So, how do I rename an already-established tag in the editor?

soft shard
jaunty sleet
#

Can someone take a look at my method here? https://paste.ofcode.org/DPqkLfm69k4NZp627nZHk It is moving an object off and on screen, while rotating it so it looks at the camera. When the object is on screen, it rotates from another part of the script, so when it moves back off screen it has to take into account the starting rotation of the object so it doesn't snap the rotation to a new value. However that part of it is not working. In my script, I am taking the look rotation and rotating it by the starting rotation to try to prevent this using quaternion multiplication. Can anyone see where I am going wrong?

soft shard
wild bane
river sentinel
soft shard
#

If your "static" point has objects between it and your AI, pathfinding can make sense, the goal of pathfinding is to find the shortest path to get to some location while avoiding stuff preventing you from going in a straight line to it, if you dont have that problem, then I think MoveTowards/Lerp sounds fine, though im not an expert with AI

soft shard
# wild bane By overrides, I mean: does it overrides it temporarly while there are active col...

If theres an active collision and then you ignore the layers, the next frame it should apply, if its a layer ignore and not a ignore between 2 colliders, so I believe until you change the scene state or call ignoreCollisions and pass true for the last param, it should continue to ignore any objects on those layers, even newly spawned ones, but it wont persist in the Editor after exiting play mode, just that session

cobalt gyro
#

does anyone know a good shader course

wild bane
soft shard
# river sentinel I'm in that menu but all I can do with tags is delete them, unless I'm missing s...

Oh, maybe something changed and its only for layers now, its been a while since I had to edit a tag, you could delete and remake it then, otherwise an alternative that comes to mind would be to edit the actual asset file for Tags & Layers, located in YourProjectRootFolder/ProjectSettings/TagManager.asset, you can open that with a text file, if you get non-human letters when you open it, you may have to go to "Edit > Project Settings > Editor", and make sure under "Asset Serialization", the mode is set to "Force Text", though I think thats a few steps for 1 tag change, and id caution making changes outside Unity this way (alternatively I think you can do it through editor scripting but also seems like an overkill approach to just recreating the tag), maybe theres another way im not thinking of atm

soft shard
wild bane
#

But basically, I have X objects in the scene

#

I have some conditions that enables/disables object/object collision

#

Every object is at the same layer

#

So there is only this condition check that makes them collidible or not for each other

#

Based on some flags

#

These objects have CharacterControllers only

soft shard
wild bane
#

Im using the first one, but no lucky. Maybe it doesnt work for Character Controllers?

#

Also, I have no Rigidbodies, if that matters

soft shard
muted helm
#
    {
        Debug.Log("Print");
        InsertLine("Input Anything...");
        Debug.Log("Read");
        yield return StartCoroutine(Read());
        Debug.Log("Cls");
        Clear();
        Debug.Log("Print _in");
        InsertLine(_in);
    }```
```    private IEnumerator Read()
    {
        while (!isInputReady)
        {
            yield return null;
        }

        isInputReady = false;
    }

Adding a console. Attempting to wait for the Read coroutine inside of the Main coroutine, which is being started by executing StartCoroutine(Main());, however the Main coroutine just executes all the way through without waiting for Read to finish Executing.
What is the proper way to wait for a coroutine in another?

leaden ice
#

What makes you think it's not waiting

muted helm
#

It immediately executes before isInputReady is made true.

leaden ice
#

How do you know? You need to add more logs

#

Including logging the value of isInputReady

#

And logs inside the other coroutine

#

Maybe it's already true

#

So it only waits a single frame

muted helm
#

Ah boom, I'm a dumbass

#

Was setting isInputReady in my print line method and not my get input method

#

Runs fine now. Thanks for knocking some sense into me

soft shard
#

Unrelated to your error, though if all your Read coroutine does is use a while loop to wait, why not use a WaitUntil yield instead of a while loop? The results should be virtually the same but you wouldnt have to have a coroutine that just yields null then

static matrix
#

can I double-derive something
like maybe make an object derive from Damager but also Interactable

#

or I could just make two scripts

#

thats probably easier

leaden ice
soft shard
leaden ice
#

Better option though is to just split those things into separate components, imo

muted helm
static matrix
#

yeah
and I dont understand interfaces, so ill just make two comps

noble surge
#

i'm using nav mash to make a car follow a destination like this

#

Any idea to make the car get a path like this instead?

lament void
#

<@&502884371011731486>

#

I need help

vagrant blade
lament void
#

Well it's not

#

I'm making a vr game you see.

#

And I accidentally deleted the main camera

#

And when I load the apk it's just the old grey void and sky

#

Do you know how to fix this?

vagrant blade
#

Good luck 🤞

potent sleet
#

You probably want to move Manhattan distance only

#

Somehow not to cut corners though

#

If you want to use navmesh is still possible if you put the points carefully on the mesh

scenic hinge
rigid sequoia
#

after completing my bro's code c# course do you recommend going towards scripting in unity?

#

I'm learning c#

#

in order to script for vid

#

just starting

scenic hinge
rigid sequoia
#

k!

#

tx!

leaden solstice
scenic hinge
#

As a matter of fact they are the least suspicious implicit operators I have lmao

#

I dont know why it says its null

#

I didnt even know a bool could be null

#

actually not true

potent sleet
#

Only if marked nullable values can

leaden solstice
rain minnow
potent sleet
scenic hinge
scenic hinge
leaden solstice
#

You defined implicit operators so to allow writing that code

scenic hinge
#

Respectfully, I get your point of view, but Its basically just implicitly casting a bool to a scriptable bool which is just a bool property

#

It'd be less sus if scriptable objects werent built different

leaden solstice
#

Which will secretly create new SO instance and won't work consistent with operators like ==, sure

scenic hinge
#

I suppose thats a bigger issue, I didnt think about that

#

I doubt that will matter at my games scale though

#

Ill try to fix that

rain minnow
#

This isn't a bool property its an SO which is a class that is created when you Implicitly assign a bool to it . . .

scenic hinge
#

Well is there any other way to return a static SO

leaden solstice
#

Why are you using SO in the first place

ashen yoke
#

what are you doing?

scenic hinge
#

Because its a lot easier for my buddy to not have to mess with code and still link useful information

ashen yoke
#

using navmesh for traffic is not how its usually approached

#

i think nobody approaches this task using navmesh

noble surge
ashen yoke
#

maybe with quad/cubic/bezier depending on how steering is handled

#

CS simulates traffic using point graph and steering behavior afaik

#

if you dont want to code pathfinding over point graph yourself the A* pathfinding project supports point graphs

#

all you need is to construct the graph with your own road pieces

#

or however you are making roads

#

theres a lot there, you can do multilevel graph, that only has major intersections, that one is used to compute the big path

#

then the main graph with all nodes you only compute path to the next target of the long path

#

the most straighforward optimization for massive cities

rigid sequoia
#

this look kinda complete

#

is it?

prime sinew
# rigid sequoia this look kinda complete

Game dev is a constant learning process. There's no one course that will teach you everything you will ever need. And you sure as heck won't retain everything in your first go

#

So there's no complete, but a good base perhaps

rigid sequoia
#

tx!

short wing
#

Guys, is there a better way to setup a C# property (without a backing field, get and set are functions taking data from transform) in the inspector ?
For example: i have a camera that orbit my planet, i want to setup the properties: coordinates + zoom and change the transform accordingly.
I have a working code, i want to show/edit in inspector.
The only two ways are building a inspector from EditorGUILayout or setting a backing field.
Any better way ?

prime sinew
#

I think the syntax is something like field:SerializeReference.

It's an attribute

short wing
#

Doesnt seen to work in this case, its to serialize a object reference.
In my case Coordinate (struct) is a result from the actual transform. I wanted to expose it in the editor without having to rebuild its fields manually through EditorGUILayout. But thanks

short wing
#

yes, i can use it to set a backing field to read/write from and reapply on validate

#

Thats the way you would do ?

light rock
#

if i understand your problem correctly, then yes. i would do something like OnValidate(){ transform.position = coordinate }

#

or vice versa, whatever you need it to do

short wing
#

and to pick the value the first time, when i load the editor, would you copy the transform -> coordinate, from a awake or start ? Or validate is also called on startup ?

light rock
#

OnValidate() is called whenever any value in the inspector changes. it's only called in the editor

short wing
#

because on validate being called after changes, its ok to pass the inspector changes to the backing field "_coordinate" and posterior changes will have the actual value. But on startup it would be default. Which function would you use to acquire the value ?

#

(start, awake)

light rock
#

if the value is marked as "public" or [SerializeField] then the value stays

short wing
#

yeah, didnt occur me

#

Maybe setup for the first time on Reset

#

thank you 🙂

novel sundial
#

General design question: Is there reason to use one pattern over the other with the following coroutine calls:

private IEnumerator DoInWhile ()
{
    while (_Condition)
    {
        yield return new WaitForSeconds(0.2f);
    }

    _Done = true;
    yield break;
}

vs

private IEnumerator DoRecursive ()
{
    if (!_Condition)
    {
        _Done = true;
        yield break;
    }

    yield return new WaitForSeconds(0.2f);
    StartCoroutine(DoRecursive());
}
weak nexus
#

hey, so i made a character in blender and added bones so it rigs all good. the character looks like this image above, the bones are shown as well, i added some animations and dropped it into unity and they work fine.

now on the unity side, i want character customization to be able to add clothes to it, armor, etc., but i'm not sure how to approach that. in the second image, i parent that white underwear to the armature's pelvis bone in the unity hierachy and that works fine i mean, until the character starts walking beause the whole underwear object just rotates back and forth instead of each individual "sleeve" moving and the base staying

#

would i add "bones" to the underwear for the "sleeves" then attach those bones to the rig's thighs in unity or something

#

okay, reading a forum thread a bit, i can make bones for the "sleeves" then rotate them along with its parent?

mossy snow
weak nexus
#

ahh okay

#

thank you

halcyon venture
#

im getting NullReferenceException: Object reference not set to an instance of an object
Actor.ChangeAnimationState (System.String newState) error at line 64.

#

im new to csharp so i have no idea what to do

#

this code is in my first person combat script and it should work fine

prime sinew
halcyon venture
#

but i have it defined up there

prime sinew
#

So make sure it has a value

#

You defined it yes

#

But did you tell it which animator is it referring to

halcyon venture
#

uhhh

#

how do i do that

prime sinew
#

You'll benefit from the beginner courses on Unity learn

#

!learn

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

halcyon venture
#

theres an animator attached to the gameobject that the script is attatched to

prime sinew
#

You still need to assign the animator component to the variable

halcyon venture
#

how?

#

like getcomponent<>

#

?

prime sinew
#

Go through one of the beginner projects or watch the get component video in beginner scripting

halcyon venture
#

oh ok

#

so i use GetComponent<> right

prime sinew
#

Watch the video

halcyon venture
#

k

#

i fixed it

#
        animator = GetComponent<Animator>();

#

i put this in my Awake() function

novel sundial
tiny pollen
#

how can i make a pixel perfect camera effect for some objects only

mossy snow
rain minnow
mighty yew
#

I'm using an animator event that calls a function with an enum input, but every time its run the program gives me a NullReferenceException. I'm not sure why. Any ideas?

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

mighty yew
#
public void StartAttack(TypesOfAttacks name)
    {
        isAttacking = true;
        animator.SetBool("attacking", true);
        if (name == TypesOfAttacks.attack1)
        {
            hbcontroller.damage = attack1damage; //NullReferenceException
        }
    }

Heres the function in question

prime sinew
#

hbcontroller is null

mighty yew
#

I thought that too, but in my awake i'm making hbcontroller an object

prime sinew
#

Show code

#

There's no thought. You can just debug log it and see the value

mighty yew
#
void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        animator = GetComponent<Animator>();
        hbcontroller = GetComponentInChildren<HitboxController>();
    }
#

this is in the parent file that im inheriting from, the child file has no awake function

prime sinew
#

Show where in the hierarchy of this object there's this HitboxController component

mighty yew
#

main character has the combat controller, hit boxcontroller is on the player hitbox

prime sinew
#

You need to pass in the parameter to look for inactive objects

prime sinew
#

Look at the documentation for GetComponent in children

mighty yew
#

oh, alright thanks!

river sentinel
#
    {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(name);

        while (!asyncLoad.isDone)
        {
            yield return null;
        }
    }```Trying to get a coroutine to check for if a scene is done loading. It doesn't seem to be working.
#

no wait, it is. So why is this breaking for me (ignore this tangent but note that I will probably have questions later)

prime sinew
#

How are you calling it

river sentinel
#

Via a UnityEvent. While the scene is loading, the event GO is set as a child of a DontDestroyOnLoad so it doesn't disappear while loading. (it get flushed when the event chain is done)

prime sinew
#

You're going to clarify what you mean by breaking

prime sinew
river sentinel
#

yes

#

I think I've locked onto the issue now, but it's something entirely different that requires more explanation on how my code specifically works.

#

And possibly looking at my project directly.

#

I'll save this question for tomorrow at this rate, it's bigger than I expected and it's also midnight here.

distant crow
#

Hey all, I'm working with the new input system and trying to learn it myself and I'd like to use the Unity Events aspect of it. I have the Player Input component on the player object and I added the input actions reference to the component. I also added the reference to my player controller script to the specific event i'm looking to invoke (Move), but when I go to look for the function I wrote:
public void OnMove(InputAction.CallbackContext context)
I cannot find it. I realize I didn't provide too much info, but is there a common mistake that causes this?

gray mural
#

"CallbackContrext "

#

it's CallbackContext

distant crow
gray mural
#

give your full code

unique cloak
#

Anyone have an idea why this list might not be serialized in the inspector?

    public List<AnimalDNA> animals = new List<AnimalDNA>();

    public class AnimalDNA
    {
        public ScriptableObject DNA;
        public int num_to_initialise_on_start;
    }

I have no errors, it's definitely the correct script, neither the script nor class are abstract. I originally had a struct but some answers online for similar questions suggested a class instead, to no avail. Much appreciated

elder flax
#

give the class [System.Serializable]

#

otherwise the editor can't display it

unique cloak
#

My hero

#

thanks king 🙏

elder flax
#

your welcome

raven orbit
#

If I want to make some methods that are accessible by a script when needed, do I do this with a namespace?

wind palm
cosmic rain
raven orbit
#

I thought one of the points in having a namespace was that you could access it's methods and variables from another script

wind palm
#

It's about separating your code.

For instance Microsoft have their "core" classes in System, but if you want IO classes you have System.IO, or if you want networking you have System.Net.

These aren't "hidden", they're just not included in your script unless you "use" them or have them in a global using.

#

For instance in a game project you may have

MyProject.Actors
MyProject.Actors.Player
MyProject.Actors.Mobs
raven orbit
#

Can I make a class that extends the monobehaviour or my games main namespace and then just call it in a script that I want it in?

wind palm
#

You can technically "hide" classes that are default in .NET by doing something like:

I.E

namespace System.IO
{
  public class File { }
}

As, then when you include System.IO you'll be including your own class, not the default .NET (I did try something similar to this recently, however this code is untested to be exact - it's also not foolproof to someone using reflection).

wind palm
#

The namespace is largely irrelevant

raven orbit
#

Will it be unique to the thing that called it automatically? So if many objects use it, their data won't get messed up

#

like if the method was to return a value based off of an input

wind palm
#

An instance is unique.

raven orbit
#

Is this the method for calling an instance? SelectionManager.Instance.Function(); would get that function/method with input data relevant to only the invoker? And if it was called again at the same time by something else, there would be no conflict?

wintry crescent
raven orbit
#

I believe here it is a Singleton?

#

and does not extend any namespace

wintry crescent
#

Yes

wind palm
#

If SelectionManager is a MonoBehaviour in this case you need to adapt to the code to:
a) create a GameObject and AddComponent<SelectionManager>()
b) Find a SelectionManager component
c) On Awake/OnEnable of SelectionManager you can set SelectionManager = this

#

Otherwise your get is going to cause issues here.

raven orbit
#

So basically making a temp game object to store data for an instance adn then get's deleted when it's not needed anymore

wind palm
#

If you need it past that you'll need to tell unity not to delete it.

tidal rapids
#

Hey guys any idea if I can set the build index of a scene at runtime?

I want to be able to create a Scene using something like Scene newScene = SceneManager.CreateScene(sceneName); then set that scenes build index so I can load into that scene

prime sinew
#

I don't think you can change the index

woeful tapir
#

do u know what this error is ?

tidal rapids
#

I dont think I can load into a scene without it being in the build index right?

tidal rapids
woeful tapir
#

idk

tidal rapids
#

where you have

public class SceneMove : MonoBehaviour

does that public up there say private instead?

#

as an example

woeful tapir
#

it is public

tidal rapids
#

thats odd

woeful tapir
#

this is the problem

tidal rapids
#

is what you are referencing private?

woeful tapir
prime sinew
#

You cannot add new scenes into build settings at runtime

tidal rapids
# prime sinew You mean build settings?

Yes like when you put your scenes into the box in build settings and it assigns them a number. I want to create a scene in the game and have it load into that scene

prime sinew
#

!vs

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

woeful tapir
prime sinew
#

Read the bot message

tidal rapids
woeful tapir
#

how to make is public

#

is it the code or something ?

tidal rapids
#

try changing the onFoot var from private to public in the code

woeful tapir
#

ok that error went

tidal rapids
#

all good?

woeful tapir
#

now there is a diff error

tidal rapids
#

what is throwing this?

#

Actually is PlayerInput your script or is it unitys

prime sinew
primal wind
#

I don't see a reason why it would behave differently but if i do someEvent?.Invoke(data) from another thread and i'm subscribed to someEvent in the main thread of Unity, will that cause issues? I have a way to not be bothered by that limitation but it requires me to add Unity to my library but i kinda want it to be just LiteNetLib and nothing else

woeful tapir
#

nvm thanks a lots for helping

#

the code works

#

Thanks a lot for your time

tidal rapids
#

no problem man

cosmic rain
#

The method would run on the other thread, so you can't use unity API in it.

#

You don't need to modify your library though. You can make it the responsibility of whoever subscribes to the event. Make sure it's clear that it runs on a thread though.

primal wind
#

Oh yeah i didn't think of that XD i can just handle it in unity

#

Thanks

warm shadow
#

so I am making a Home Assistant of GPT-3.5, but my current way of doing it is not optimal, here is the current setup:

First I wait for a noise
then when I detect a noise I start recording
after recording for 5 seconds I stop
That recording then gets turned into text by a speech to text (Whisper)
then I see if that text includes the name of the home assistant
if it does I send the text to GPT-3.5 and wait for the response
when I get the response I use a TTS service to say I
When the TTS is done saying it, I start recording again for 5s
then I go through the same again but if GPT-3.5 detects an end of the conversation it will send the command [End conversation] and then I don't start recording again after the TTS is done.

Here is a list of the Issues is have with this setup:

  1. I have to first make a noise, then I have to say the name and then I can ask the question. This is too many steps.
  2. I can only talk for 5s so I sometimes have to talk fast. This is a general issue no matter how long the recording is. I want to get rid of the set recording length.
  3. If I ask a small question I still have to wait the entire 5s to get a response.
  4. I want to change it so GPT-3.5 does not have to detect an end of the conversation to end the conversation. As it is unreliable.

Here are the limitations I have:

  1. I can only either record a file or detect the loudness of the microphone
  2. The speech to text can only get a recorded clip no streaming

Here is also the code: https://gdl.space/oyavubeqoz.cs

I know a bit messy both the code and the explanation but I tried my best. In the code just focus on Update function on line 122.

knotty sun
#

And all of that sounds like it has nothing to do with Unity

steady moat
warm shadow
warm shadow
knotty sun
warm shadow
knotty sun
#

none of what you describe is Unity specific

warm shadow
#

I am aware, but that would require me to learn Python as far as I know, and i don't really have the time. The question was mostly to see if there was any thing i missed, or something simple that could be improved, but you are right, I'll come back the project when i have more time and do it properly like you said, in a console app : D

knotty sun
#

python? Why? you can make a console app in .Net C# exactly the same as Unity

heavy smelt
#

Is there any way to check the FPS of an Android Application through the Editor's Profiler ? I can see other metrics like memory etc but can't figure out where the FPS is shown when connecting the profiler to the development build running on the Android device.

steady moat
#

However, the FPS will not be representative of what you have in release mode.

#

As a development build add a substantial amount of work.

warm shadow
heavy smelt
#

@steady moat okay okay, then I guess I will use the dev options on the device to see the actual FPS, thank you very much for your remark !

hasty canopy
#

Is it possible to setup authentication system around just email ID and password using unity gaming services?

swift falcon
static matrix
#

im not sure how to phrase this, but
is it possible to set up something so you could say
"Set this to false provided nothing else is trying to set it to true"
or is that not a thing

gray mural
#

Hello, will using block be closed if I return within it?

#

I guess yes, right?

steady moat
static matrix
#

i think the issue im trying to solve is that I have multiple things that prevent sleep, but after it is set to true, I need to set it to false once all the conditions to set it to true are no longer valid, and they are spread across multiple scripts, and multiple gameObjects, so I cant have a big if check

steady moat
#

You can also use a semaphore approach.

#
private void LockSleep(){
  sleepLock++;
}
private void UnlockSleep(){
  sleepLock--;
}
private void CanSleep(){
  return sleepLock == 0;
}
rain minnow
#

Agreed, I'd use an event to update it. Send an event to add and subtract from sleep and update the counter. When it reaches 0, sleepy time!

steady moat
#
private List<System.Func<bool>> conditions = new List<System.Func<bool>>();

private void Subscribe(System.Func<bool> condition){
    conditons.Add(condition);
}

private void Unsubscribe(System.Func<bool> condition){
    conditons.Remove(condition);
}

private void CanSleep(){
    return !conditions.Any(x => x.Invoke()); 
}
static matrix
#

managing going up and down might be a hassle
the list might be more optimal for me
Ill do that

#

are objects actually destroyed when I load a new level? will it trigger OnDestroy

fervent furnace
#

depends on how you load the new scene, i heard that additive will not destroy objects in old scene

autumn cipher
#

would it make sense to instantiate a scriptable object at start and assigning it to a reference of the SO class inside monobehaviour?

#
public interface IPlayerComponent
{
    public Player player { get; set; }
    public virtual void doAwake<T>(Player player, ref T playerComponent) where T : ScriptableObject
    {
        this.player = player;
        playerComponent = UnityEngine.Object.Instantiate(playerComponent);
    }
[CreateAssetMenu(fileName = "Move", menuName = "ScriptableObjects/Player/Components/Move")]

public class Move : ScriptableObject, IPlayerComponent
{
    public Player player { get; set; }

    public float BaseSpeed = 5f;


}```
```cs
public class Player : MonoBehaviour
{
    public Move move;
    void Awake()
    {
        ((IPlayerComponent)move).doAwake(this, ref move);
    }
}```
thin hollow
#

While coding saving and loading, I've come to a problem. Currently my code uses a lot of coroutines like

        private IEnumerator BeginStun(float time)
        {
            isStunned = true;
            InputControl.Instance.SetControlState(ECState.Character_NoMove);
            meshAnimator.SetBool("Stunned", true);
            yield return new WaitForSeconds(time);
            isStunned = false;
            yield return new WaitForSeconds(1);
            if (!isStunned)
            {
                InputControl.Instance.SetControlState(ECState.Character);
                meshAnimator.SetBool("Stunned", false);
            }
        }

Can I save and restore their state? Because RN when I load a save, they just get eradicated, which breaks stuff if one of those was active when player saved (in case of BeginStun, for instance - in that save the player will never come out of stunned state, because isstunned set to "true" but coroutine that was about to set it back to "false" got lost)

static matrix
#

ughhh this is spaghettiiiiii
even I recognize it isnt going well

latent latch
#

Well, you'll need to serialize all variables of that specific state then and redo the coroutine when you deserialize the data

latent latch
autumn cipher
thin hollow
leaden ice
latent latch
#

Right, there's less overhead but you do lose the scene presence of a mono, and you cannot directly run coroutines on them. Not the biggest of deal since you can always just use a manager on the scene for that.

latent latch
steady moat
leaden ice
#

yeah that's the answer for sure. You need finer grained control of your state machine than you can get with a coroutine here, so it's time to jump off the coroutine train and build your own state machine whose state can be serialized and restored.

Coroutines are essentially just quick and easy state machines

steady moat
#

Also, in your case, I doubt that the Move will want to be a ScriptableObject.

#

It is share by what ?

thin hollow
autumn cipher
thin hollow
#

"do not use coroutine use Update" can work for some cases of course... Up until you'd need to replace two coroutines running alongside one another. °~°

autumn cipher
steady moat
autumn cipher
#

but it seems like it's not worth going through all the trouble

steady moat
#

Coroutine are not even async. There is nothing that prevent you from doing:

UpdateA();
UpdateB();
static matrix
#

if you need delays, you can use Time.Deltatime timers or Invoke()

latent latch
#

I was thinking of changing my Buff/Debuff coroutine scripts into a general container to update through on each entity instead of just firing and forgetting.

#

It comes down to waitforseconds() vs checking the time each update, but I would assume the operation time is similar.

rain minnow
latent latch
#

Oh, yeah that's a good point

rain minnow
# latent latch Oh, yeah that's a good point

Updating the buffs through each entity is better as you can pause, stop, or cancel the process if needed. Personally, I'd run each entities Update through a global updater to control all buffs (though that's not particularly needed) . . .

pure cliff
pallid cedar
#

Right now, im trying to make a gun gameObject recoil backwards, away from whatever enemy its shooting at. Ive done all the coding, just not the recoil part. Any ideas on how I would accomplish this?

frail meteor
#

Is is possible that this code gets compiled in a build only from a Windows os?
I can build locally but it fails on a remote pipeline that runs on Linux

    WebGLInput.captureAllKeyboardInput = false;
#endif ```
leaden ice
#

that will only be compiled for a webgl build

frail meteor
#

and indeed the target platform is webgl build

#

also is it normal that If I try to run that code from the editor I get an error?

#

I read that WebGLInput is specific to WebGL app

thin hollow
pure cliff
#

though not sure what you are trying to do there ngl

#

but when you see 0.5f twice in your conditional thats usually a sign you can simplify it out, like a math equation

molten isle
#

Hey I need help, my boost is propelling me in the direction the player is facing, not the forward direction of the boost. Here is the script:https://gdl.space/ogigokehip.cpp and that is the boost model, which as you can see I want to boost the player in that direction the boost is facing. (the script is on the PLAYER not boost!!)

thin hollow
latent latch
#

Ideally, you should just rotate the booster into the desired forward direction

pure cliff
latent latch
#

^

molten isle
pure cliff
#

I live in 2d land though so quaternions are something I havent learned the methods on, but you want the X/Z vector on that plane for what way its "facing", there's a method for that IIRC

thin hollow
frail meteor
molten isle
#

but I want it so even if I rotate the boost it will work, or else every time I have to find the direction

pure cliff
#

every update you just subtract off Time.DeltaTime from your existing buffs/debuffs, then do a pass for if any of them have dipped below 0 and invoke code for em

#

prolly then want Strategy Pattern to handle various debuffs and what they do given that info

#

prolly something like

public interface IBuffStrategy
{
   int DebuffId { get; }
   void Process(DebuffContext context);
}
spring creek
molten isle
thin hollow
# pure cliff `if (remainingTime > 0)`

Yeah, right, so if I have function

void DoAFlip()
{
if (remainingTime < 1)
  DoJump();
if (remainingTime < 0.5)
  TurnAround();
if (remainingTime =< 0)
  Land();
}

by the time it's time to call Land(); it will still be calling DoJump and Turn Around on each frame. Unless I give it very tight "if" conditions... Which might cause it to skip Jump() or TurnAround() completely if the player's framerate is shit......

spring creek
molten isle
#

Ok thanks, I will try it

latent latch
pure cliff
#

then maybe like

public class PoisonDebuffStrategy
{
   private GameState GameState { get; }
   public PoisonDebuffStrategy(GameState gameState) {
       GameState = gameState;
   }

   public int DebuffId => DebuffIds.Poison;
   public void process(DebuffContext context)
   {
     GameState.Player.Debuffs[DebuffId].RemainingTimeMs -= context.DeltaTime;
     var actualTime = context.DeltaTime;
     if (GameState.Player.Debuffs[DebuffId].RemainingTimeMs < 0)
        actualTime += GameState.Player.Debuffs[DebuffId].RemainingTimeMs;

     GameState.Player.Life -= actualTime * this.damagePerSecond;
   }
}
spring creek
latent latch
#

oh yeah, probably dont want to do that haha

thin hollow
pure cliff
thin hollow
pure cliff
#

or just use the physics engine and then have their animation be purely based off the couple vectors you have to work with (velocity and is collided with ground)

pure cliff
#

your serialization issue with starting the game and saving it? no that should be solved with what I posted largely

thin hollow
# pure cliff whats "the same problem"?

the problem of "how do I run each part of the function exactly once, ensuring I won't skip it if player's framerate is shit, and with a code that's human-readable, and without multiplying a shitload of bools"

pure cliff
#

I did forger their prolly should be a > 0 check at the start, and short circuit out of the debuff no longer has duration left

pure cliff
#

you're gonna need to do math, basically, to figure out where they were, and based on time transpired from the last frame, where they now outta be

#

"be" in the sense of total game state of all relevant stuff. Position, velocity, animation, life, all that jazz

#

luckily unity has handy methods like Lerp and Slerp to help facilitate this, animation curves, etc

#

in the case of the code you wrote above for example, it looks fine to me. I would just make sure that the logic of Land() overwrites the logic of TurnAround

#

such that if both of them fire off in the exact same frame, Land()'s mutatations "trump" TurnArounds and it takes precedence

steady moat
#

A really simple implementation would be:

void Update()
{
  State next = current.Update();
  if(next != current) {
    current = next;
    current.Enter();
  }
}
steep saddle
#

I have a script that holds a couple variables. I want those variables to be readonly but accessible by every other script, except for one which I want to be able to modify the variables. How can this be implemented?

latent latch
#

plain c# or mono?

leaden ice
pure cliff
#

and if its a list, use Readonly list property backed by a normal list as a field

#

actually Im curious @leaden ice do you know of any kind of readonly list in C# that provides real time access to a "bound" normal list? like where any mutations to the original list will be reflected by the readonly one?

#

without having to do re-allocations

leaden ice
steep saddle
pure cliff
leaden ice
leaden ice
pure cliff
#

that was easy

#

10 years and I honest to god was today years old when I learned that List implement IReadOnlyList

leaden ice
#

And why shouldn't it? It's just a subset of the List functionality!

pure cliff
#

@steep saddle
Private: Only this class can access it
Protected: This class and its inheritants can access it
Internal: Same Namespace can access it
Public: Everyone/Everything

steep saddle
# leaden ice that's the point of it being private

Okay, so just so I'm understanding... I have my structContainer script with public getters, and I have my structSetter script (which does more than just set the struct, but it is part of its functionality). How does structSetter set it?

leaden ice
#

What's the use case here

pure cliff
#

if so, thats what the constructor is for

steep saddle
# pure cliff <@436948512337559552> Private: Only this class can access it Protected: This cl...

I have a bunch of microcontrollers connected to buttons, toggles, rfid readers, lights, etc. I have a Port handler script that does the work of decoding/processing the Serial packets. I want to have corresponding game objects for each of my toggles and buttons and whatnot, whose state can then be read by other scripts. But the "setting" of the toggle object's state should only be done by my port handler script

pure cliff
pure cliff
#

you can have the get functionality exposed on the Interface, but the Class has the setter also exposed.

Your service can have the class version of your objects, but its methods all return the interface

public interface IFooEntity
{
   string Bar { get; } // <- note the lack of a set here
}
public class FooEntity : IFooEntity
{
   public string Bar { get; set; } // <- Note how the set is public here
}
public class FooService
{
   private FooEntity MyFoo { get; } // <- We have the class, not the interface ref

   //      v--- note how this returns the interface, not the class version
   public IFooEntity SetFooText(string text) 
   {
      MyFoo.Bar = text;
      return MyFoo
   }
}

Note that when handed a copy of IFooEntity they can only read from it, the setter is not exposed

#

Interfaces, as their name sort of entails, are primarily useable in this way, by acting as a "mask" that can cover up and specify what functionality is exposed vs not

steep saddle
#

Okay, thank you. Trying to process it all

#

In the specific example I listed, I would pass the IFooEntity to anything meant to only read Bar (what does the "I" imply, by the way?)

#

Do I have it right?

pure cliff
leaden ice
pure cliff
vale bridge
#

Is there a sort of code review channel here :>

pure cliff
steep saddle
#

Okay so, this is the script I would put on a given toggle object? I don't quite understand what is happening with the get; and set; up top, nor do I know what I'm returning the toggle entity in setState? Also, is set state meant to be an interface or is toggle? Currently I'm getting an error by trying to return toggle.

public interface IToggleEntity
{
    bool state { get; }
}

public class ToggleEntity
{
    public bool state { get; set; }
}

public class ToggleSwitch : MonoBehaviour
{
    private ToggleEntity toggle { get; }
    public IToggleEntity setState(bool newState)
    {
        toggle.state = newState;
        return toggle;
    }
    bool state = false;
}
pure cliff
carmine umbra
#

I can play midi inputs but not outputs and read midi. anyone capable to help me with that? I've done research but can't find a solution till now or someone who understands how to do it

#

have installed DryWetMIDI and NAudio

river sentinel
#

OnSceneLoaded doesn't seem to be running when the scene has loaded. Or can it not run from DontDestroyOnLoad()?

pure cliff
#

But I mean, your ToggleSwitch can implement the interface directly, you can inherit from 1 class but you can implement infinite interfaces, you can 100% just do

public class ToggleSwitch : MonoBehavior, IToggleEntity

if you like, it super depends on how your other code gets the toggle switch

steep saddle
river sentinel
#

from an object that gets set to DontDestroyOnLoad:

rigid island
river sentinel
#

define "sub"

pure cliff
rigid island
simple egret
#

This method isn't referenced anywhere, did you forget to subscribe to the SceneManager.sceneLoaded event?

rigid island
#

oh wait isn't it SceneManager.activeSceneChanged?

pure cliff
#

If however, you want your IToggleSwitch to be implemented by a POCO, I dont think those can be serialized fields

river sentinel
rigid island
soft shard
simple egret
rigid island
#

ahh right..

pure cliff
rigid island
pure cliff
#

in your example code you wrote there, ToggleEntity is a POCO for example

leaden ice
river sentinel
rigid island
#

so you get a(current scene & next scene)

#

not sure this the method you want tho

#

sceneLoaded could prob work fine, but did you actually subscribe to the event. Show the whole script @river sentinel

river sentinel
#

ended up going with this and the Debug.Log fired off properly

rigid island
#

it's good practice to cleanup

#

avoid some weird leaky

river sentinel
#

ah, thank you for that

#

one more question, not for fixing a problem or anything but just for my understanding: A missing GO is treated as just null, correct?

leaden ice
river sentinel
#

if a script tries to reference it it'll act like it is null, right?

leaden ice
#

obj == null will return true

#

and dereferencing its fields will give MissingReferenceException

#

but it's not a true null

river sentinel
#

or check "if null then this" will return as it beign null

leaden ice
river sentinel
#

okay good

weary hollow
#
    private bool canMove = true;
    [SerializeField]
    float smooth = 5.0f;
    [SerializeField]
    float tiltAngle = 20.0f;

    private void Update() {
        if (canMove == true) {
         //get input from GameInput.cs
         Vector2 inputVector = gameInput.GetMovementVectorNormalized();
         //input to movement
         Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
         transform.position += moveDir * moveSpeed * Time.deltaTime;
         
         //goofy movement physics
         float tiltAroundZ = Input.GetAxis("Horizontal") * tiltAngle;
         float tiltAroundX = Input.GetAxis("Vertical") * tiltAngle;
         Quaternion target = Quaternion.Euler(tiltAroundX, 0, tiltAroundZ);
         transform.rotation = Quaternion.Slerp(transform.rotation, target,  Time.deltaTime * smooth);

         //rotation interpolation
         float rotateSpeed = 12f;
         transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
        }
    }```
cedar jolt
rigid island
#

the clipping in the ground probably

#

or smacks its head or w/e

cedar jolt
#

If you want to have fun with camera mouvement, I recommend looking at this here : https://youtu.be/mr5xkf6zSzk

GDC

In this 2015 GDC tutorial, SMU Guildhall's Squirrel Eiserloh takes a dive into the world of 1D nonlinear transformations to help game programmers make better games.

Register for GDC: http://ubm.io/2gk5KTU

Join the GDC mailing list: http://www.gdconf.com/subscribe

Follow GDC on Twitter: https://twitter.com/Official_GDC

GDC talks cover a ran...

▶ Play video
weary hollow
weary hollow
cedar jolt
#

Ho I didn't see that.

somber imp
#

is it a bad idea to use a rigidbody for a 2d character controller?

pure cliff
#

do you want to use physics? if so you use the 2d rigidbody yeh

rigid island
cedar jolt
#

LateUpdate() happens after Update()

weary hollow
weary hollow
weary hollow
weary hollow
leaden ice
#

.transform exists

#

no need to ever use GetComponent<Transform>

weary hollow
#

ok cool

cedar jolt
#

Just write "transform" in your script

#

it will get the tranform of the current object

river sentinel
molten isle
rigid island
molten isle
molten isle
fair jackal
#

Hey guys, where would i go for netcode for gameobjects help

fair jackal
#

Got it

cedar jolt
molten isle
#

i had that

rigid island
molten isle
#

doesnt change

fair jackal
#

Ah there’s teo, okok

molten isle
rigid island
#

does it point where arrow is ?

molten isle
#

yes the axis are correct

steady moat
#

Is the correct force being applied ? I feel like your movement script might just override your change.

rigid island
molten isle
molten isle
rigid island
#

no shit

#

are you using .velocity ?

molten isle
#

wait

rigid island
#

if you are it overrides all forces

molten isle
#

i dont see no .velocity

#

here is the player mov script:

rigid island
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

molten isle
#

btw the posses shit shouldn't affect it

rigid island
#

maybe your velocity limiter

#

is coming into effect

#

if (flatVel.magnitude > moveSpeed && grounded)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}

molten isle
#

How?

rigid island
#

cause it would resort to .velocity

#

which would override it

#

that's if that even hits that statement

molten isle
#

but how

#

does that have anything to do with the direction ?

#

like the force is being applied fine

rigid island
molten isle
#

no

#

Lemme try

rigid island
molten isle
#

nope doesnt appear when I go through the boost

#

this was it

#

I didnt get any message

rigid island
molten isle
#

wait

#

the same as with jump

#

just propells me in the direction im facing

rigid island
#

Boost is on player right ?

molten isle
#

The script is on the player yes

#

like I said the boost model has no script, just a trigger collider

#

thats why i used other.transform

rigid island
molten isle
#

global

#

but even if the axis were messed up

rigid island
molten isle
#

I would be propelled always to one direction no?

#

ok

#

what do you mean by tag boost

rigid island
molten isle
#

the axis in local

rigid island
#

thats interesting

#

the forward is up..

molten isle
#

Should I change it to up

#

Like

simple egret
#

Blender export, it seems

molten isle
#

other.transform.up

molten isle
rigid island
#

I would fix the pivot personally

simple egret
#

You should configure the exporter to use Z as forwards, and Y as up

molten isle
#

okay it works

#

its just

#

really

#

really weak

#

let me turn it up

#

ok this is weird

#

I turned it up

#

by *10

#

and its the same

#

just a really weak push

#

but atleast correct direction

#

im gonna do *100

rigid island
molten isle
#

ok I changed it in the inspector and I got yeeted to heaven so it works, thanks

fiery wagon
#

Hello everyone, I can do whatever I want as software in unity, but I write unhealthy code. For example, I always use bool or something. How can I advance myself?

soft shard
fiery wagon
fiery wagon
marble spindle
#

its canon event bro I underestimated hardware and still do idk but bool aint nothing kekW

somber nacelle
leaden ice
fiery wagon
#

for example

#

I usually write like this

simple egret
#

The whole bunch of GetComponent() and FindGameObjectWithTag() calls is what would hurt the performance the most here, not booleans

#

Especially when it's done ~50 times a second

fiery wagon
#

I'm trying to learn the principle of working with different classes. I can't. looking for advice

spring creek
#

Just find the ship once in start

#

Are there more than one?

gray mural
fiery wagon
gray mural
#

oh, that wasn't a question

#

I am sorry @spring creek

spring creek
spring creek
gray mural
spring creek
fiery wagon
gray mural
#

you mean you don't know why you shouldn't just paste everything in one script?

#

or why you should make multiple classes in one script?

fiery wagon
gray mural
river sentinel
#

So, is it possible to make a UnityEvent that has a Vector or multiple arguments? So far, those functions seem to be unavailable in the inspector.

fiery wagon
spring creek
gray mural
river sentinel
#

trying to get one that moves a player to certain coordinates with a Vector3, but I can't put that function in the UnityEvent.

fiery wagon
gray mural
#

just make sure not to inherit classes from MonoBahaviour in one script

gray mural
#

you can make classes with quite a similar meaning in one script

#

if you load data from json, you probably will have data class in the same script

fiery wagon
gray mural
#

json you mean?

#

I don't think you need it now

river sentinel
#

MovePlayer(v3) and RotatePlayer(quat) are the notable ones here.

gray mural
#

I have just gave you an example that first came to my mind @fiery wagon

fiery wagon
gray mural
#

see some tutorials

#

google => json with unity

#

"loading data from json unity"

#

"saving data to json unity"

fiery wagon
#

ok i will look. Thank you for your attention.

gray mural
#

: Event<Vector3>

#

: Event<Quaternion>

river sentinel
#

Please course-correct me here.

gray mural
gray mural
#

you should inherit from event

#

you create your class that inherits from Event of type Vector3 first

#

then serialize it in another class

#

subscribe it

#

and Invoke when needed

#

pretty easy 🙂

river sentinel
#

am I able to set the coordinates in the inspector this way?

somber nacelle
gray mural
somber nacelle
river sentinel
#

that's important here so I don't need to do a wild workaround

gray mural
#

with [Serializable]

#

should work

#

I have never tested it

#

and see this post

river sentinel
#

still don't see it

somber nacelle
#

you have to make a field of type UnityEvent<Vector3>

#

inheriting from UnityEvent<Vector3> to create your own serializable class is not necessary

gray mural
gray mural
somber nacelle
gray mural
#

like are you changing source code or what?

#

probably no

river sentinel
gray mural
#

not yours

#

you should try to find it in your class

river sentinel
#

it's EventCollection, not EventCollections

gray mural
#

you will just find your method there

#

read the documenation I have sent how to do it

#

and don't forget that you don't have to create your custom event class

#

as boxfriend has previously mentioned

muted helm
#

What's the correct way to remove a listener added with a lambda like this?

unityevent.AddListener(() => { // Whatever
});

Or will it automatically disappear as it exits the scope of the parent method?

somber nacelle
#

store the lambda in a delegate variable and pass that to AddListener or subscribe using a method

hard viper
#

i feel like i’ve done something like that before, where the lambda stays in scope

#

but I’m not sure if I used a delegate

somber nacelle
#

then you can remove the listener using the delegate variable or the method

hard viper
#

I have a bit of a graph theory coding problem.
I have a directed graph that may contain cycles and logic at specific nodes to turn them on/off with electricity. During runtime, certain nodes will light up and pass electricity to any node it can reach. The issue is that some bits of logic might run into conflicts when I have cycles, and I’m not sure how to resolve them.

hidden flicker
#

how do i get "rb.velocity = (moveDir.z * transform.forward + moveDir.x * transform.right).normalized * runForce;" to ignore the y velocity and leave it unchanged?

leaden ice
#

something along these lines

hidden flicker
leaden ice
hidden flicker
leaden ice
#

no

#

I'll leave it as an exercise for the reader

hidden flicker
#

a what

#

my dude you're not giving me homework lmao

#

you're good though, thanks for the help anyways

fleet delta
#

I have a question about the math in an algorithm I found. Is this the place to ask that question?

latent latch
#

kinda, unless it's 99% math

#

probably better to find a more math focused discord

quasi scarab
#

Hello, I'm new to Unity so sorry if this is a stupid question, but I just can't figure it out or find anything relevant.
I have a unit prefab that work perfectly fine until I put 2 of them in the scene, if I do, then when I hit play they all disappear except for 1.
Does anyone know how to fix this?

The object returns when you stop it, it disappears from the hierarchy as well.

leaden ice
#

can't say anything more than that without seeing the code, naturally

solemn raven
#

hi ,
i'm unable to open cginc files on visual basics all the sudden
when I open any file it opens limetext instead, how do i fix this ?

quasi scarab
leaden ice
#

at an inappropriate time

solemn raven
#

i tried unloading and reloading the project in VS 2 times , didnt work , restarting unity didnt help either

quasi scarab
thin hollow
#

My GameManagerGlobal script is added to "DoNotDestroyOnLoad" on Awake:

    private void Awake()
    {
        // If there is an instance, and it's not me, delete myself.
        if (Instance != null && Instance != this) 
        { 
            Destroy(this); 
            Destroy(gameObject);
            return;
        }
        Instance = this; 
   ->     DontDestroyOnLoad(gameObject);
        gameState.Reset();
        
        GetComponent<PlayerInput>().enabled = true;
        GetComponent<InputControl>().enabled = true;
        if (gameState.currentLevel == "")
            gameState.currentLevel = SceneManager.GetActiveScene().name;
        SavePreferences("Default_Game_Settings");
        LoadPreferences();
    }

, but I still get
MissingReferenceException: The object of type 'GameManagerGlobal' has been destroyed but you are still trying to access it.
when I change levels. What I might be doing wrong?

leaden ice
thin hollow
leaden ice
#

basically I'm confused why you highlighted this line:

DontDestroyOnLoad(gameObject);
If that's not where the error is

thin hollow
# leaden ice Show the actual full stack trace for the error
MissingReferenceException: The object of type 'GameManagerGlobal' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.MonoBehaviour.Invoke (System.String methodName, System.Single time) (at <4a31731933e0419ca5a995305014ad37>:0)
GameManagerGlobal.OnSceneLoaded (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) (at Assets/Cliffworld/Scripts/CoreGame/System/GameManagerGlobal.cs:160)
UnityEngine.SceneManagement.SceneManager.Internal_SceneLoaded (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) (at <4a31731933e0419ca5a995305014ad37>:0)

Line 160 is the Invoke line.

leaden ice
thin hollow
leaden ice
thin hollow
# leaden ice can you show where you are subscribing to the onSceneLoaded thing?

Here's the whole set of functions involved in the level change, JIK:

public void ChangeLevel(string levelName, string spawnPoint = "none", bool loadSave = false)
    {
  ->      SceneManager.sceneLoaded += OnSceneLoaded;
            playerState = player.GetData();
            if (!loadSave)
                SaveSceneData();
            nextLevelName = levelName;
            levelSpawnPoint = spawnPoint;
            levelChangeIsSaveLoad = loadSave;
            DevLog.Log("Loading scene '" + levelName + "'...");
            //TODO: change level fade-out
            inGameplay = false;
            InputControl.Instance.SetControlState(ECState.Character_NoMove);
            Invoke(nameof(BeginChangingLevel),2f);
    }

    public void BeginChangingLevel()
    {
        SceneManager.LoadScene(nextLevelName);
    }
    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        DevLog.Log("Loaded scene "+scene.name);
        if (scene.name != "MainMenu")
        {
            //wait a frame or two to ensure everything loaded and set itself up
            Invoke(nameof(LoadingTimeout),0.1f);
        }
        levelSpawnPoint = "none";
        gameState.currentLevel = scene.name;
    }
    private void LoadingTimeout()
    {
        SceneManager.sceneLoaded -= OnSceneLoaded;
        FinishChangingLevel();
        inGameplay = true;
    }```
leaden ice
#

SceneManager.sceneLoaded += OnSceneLoaded; should go in Awake and SceneManager.sceneLoaded -= OnSceneLoaded; should go in OnDestroy

Remove SceneManager.sceneLoaded += OnSceneLoaded; from the ChangeLevel function

thin hollow
leaden ice
#

yes it will fix the error

#

the other option is to leave it as it is but add SceneManager.sceneLoaded -= OnSceneLoaded; inside OnSceneLoaded

thin hollow
#

Okay, thanks, I'll think of other way to stop OnSceneLoad from firing.

thin hollow
solemn raven
#

guys
one of cginc files doesnt open on visualStudio because of this error An error occurred in 'Assembly-CSharp' while attempting to open 'filename.cginc

#

what should I do ?

#

it was working before, but I think my pc had unplaned shutdown and this happened

solemn raven
#

ok I have noticed that the code have turned into 00000000000000000000 somthing like that

#

is it reversable ?? , i have an older version of the file , should i go back to it or is it fixable ?

#

I think the file is busted , that looks scary but it actually works , it does what it supposed to do , its just not in form of code anymore.

marble spindle
#

ayo what is this for

solemn raven
#

oh its for shader basically, but looks like it's corrupted without a way to fix it, i've no idea why it gone to this for an unexpected shutdown, if i remember correctly my pc was on sleep mode , yet the file got corrupted nonetheless, im bking everything up now.

vocal root
#

If random range is maxExclusive shouldnt I be doing this? bc sometimes is out of range

#

is it really maxEclusive? because i dont think so even if its said when hovering random range

buoyant crane
vocal root
#

oh

#

thats nice to know

#

thanks!

ruby wing
#

I swear the parameter name on the function is literally maxInclusive

outer shuttle
#

Will anyone like to he,o with my game

sturdy pagoda
#

hey so for some reason my "looking around" script only works by looking up and down< i cant look left or right, im pretty sure ive done everything right tho

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class ViewingScript : MonoBehaviour
{
    [Header("Mouse Settings")]
    public float mouseSensitivity = 1;
    private Vector2 _currentRotation;

    private void Update()
    {
        DetermineRotation();
    }
    private void DetermineRotation()
    {
        Vector2 mouseAxis = new(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

        mouseAxis *= mouseSensitivity;
        _currentRotation += mouseAxis;

        _currentRotation.y = Mathf.Clamp(_currentRotation.y, -90, 90);

        transform.root.localRotation = Quaternion.AngleAxis(_currentRotation.x, Vector3.up);
        transform.parent.localRotation = Quaternion.AngleAxis(-_currentRotation.y, Vector3.right);


    }

}
steady moat
#

Try this instead

    [SerializeField] private float speedH = 2.0f;
    [SerializeField] private float speedV = 2.0f;

    private float yaw = 0.0f;
    private float pitch = 0.0f;

    void Update () {
        yaw += speedH * Input.GetAxis("Mouse X");
        pitch -= speedV * Input.GetAxis("Mouse Y");

        transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
    }
spring creek
# buoyant crane for floats

I feel like that makes sense, otherwise it would be something so incredibly close to the upper bound it would be rounded to it in many cases anyways. Right?

buoyant crane
spring creek
cosmic rain
solemn raven
#

all other similar files even with the same formate opens normally with the code written on it and perfectly working as well

leaden ice
#

i mean the file clearly got corrupted somehow

#

hopefully you're using version control

solemn raven
#

i had my own backup file from yesterday and I have just finished redoing all the code.

solemn raven
cosmic rain
#

Okay

solemn raven
#

sorry, i signed a Non-Discluser.

#

i will just try to understand how is it still working where all what is written on it is a bunch of zeros , i havent seen a single 1

#

more on that later.

#

that might be the best encryption method LOL

tawny mountain
#

CanSomeone help me I forgot how to make my character move in the forward direction

private void FixedUpdate()
    {
        if (playerRigibody != null)
        {
            playerRigibody.velocity = new Vector3(inputVector.x, 0, inputVector.y) * speed;
        }
    }
#

I think I use vector3.forward right?

somber nacelle
#

or transform.TransformDirection

silk cairn
#

how could I only have a parameter if a bool is enabled?

tawny mountain
spring creek
somber nacelle
silk cairn
#

for a scriptable object

#

basically, if something is craftable I want it to have a requirements parameter

spring creek
#

Hmmmmm, i do not know. I know you can have multiple constructors.... but...

silk cairn
#

I thought about doing the craftable ? reqs : null or something

somber nacelle
#

on the line you have selected is fine, or immediately above that line

#

bro what

#

pass in your input multiplied by speed to TransformDirection, not Vecto3.forward. and use the returned value to assign to velocity

#

transform.TransformDirection(Vector3.forward) would just return the same thing as transform.forward

unreal valley
#

Is it possible to GetComponent in EditMode?

unreal valley
pure cliff