#💻┃code-beginner

1 messages · Page 537 of 1

naive pawn
#

no, assigning components on the current gameobject just really don't have to be done via inspector

#

...no, just no.
using examples that aren't viable isn't a good way to teach someone an unrelated skill.

placid oxide
#

Why when I build the game, it's missing a whole script and an image, but works fine in test mode?

steep rose
#

it is a viable way to assign something? They will see the error and try to fix it, not just copy code and see that it works and forget about it

naive pawn
#

it's not viable for static, this-gameobject components

#

inspector fields should be for parameters for that component. why set components in the inspector if they're never going to change?
you'd have to parse it when reading, or filter it out mentally, and make sure to not accidentally touch them
you'd either have to set up prefabs for everything, or set those components every time you attach that component
if you ever want to add that component at runtime, you'd have to make sure to set all those fields

why not just let the component manage its own, unchanging references?

#

setting these via inspector is just more work, more stuff to accidentally touch, more stuff to read, obscuring the actual parameters for the component

swift crag
#

I use GetComponent in situations where the object I want absolutely must exist on the same object as my component, and where this will never change

#

I do generally prefer to use a serialized reference

steep rose
#

yes if you are using a prefab or if the switch out in runtime/need it on that gameobject then sure use getcomponent, also you'd have to parse it when reading, or filter it out mentally, and make sure to not accidentally touch them? It's literally as easy as dragging and dropping either the component or the gameobject into the fields and just not touch them anymore, that is it. It is not hard to do and is fine for their project to learn the ropes

swift crag
#

it's really not that deep, though

#

😉

naive pawn
#

do you not know what "accidentally" means lmao

#

sure it's not hard to not intentionally touch them

#

accidentally doesnt' care about what's hard or not
but assigning it on startup makes it impossible to accidentally mess up the reference

steep rose
#

how would you accidentally drag and drop a component onto a field and not see that you just did that to the wrong field

#

that does not make any sense

naive pawn
#

like i said before, examples of unviable situations aren't good examples
if you use this as an example to "learn the ropes", this would be the pattern going forward
do you think a beginner would have the foresight to not have way too many components and parameters on the same component
you're just increasing the future workload with an example that has much better, actual real use-case examples

#

like _walkSpeed, maybe focus on that and recommend setting that via the inspector, instead of the thing that gets no benefit and only has downsides by being in the inspector

naive pawn
#

yes if you are using a prefab or if the switch out in runtime/need it on that gameobject then sure use getcomponent
these are not the situations i mentioned, btw.

#

im saying that, if you use your method of setting stuff in the inspector, you can't reuse the component without going through the process of dragging the same gameobject in every component field, and making sure not to drag the wrong one in

or you'd have to make a prefab, just to reuse a component

that just doesn't make sense

#

setting stuff in the inspector does not have any reasonable upsides, and it has quite a few significant downsides

#

ive made my points, we're going in circles, im done here

lapis veldt
#

Hello. I come with a new problem: I made the character movement using a character controller. The question is: how do I make the character "stick" to the ground? because when I press play, the character is levitating

frail hawk
#

make the collider smaller

wintry quarry
#

or just.. move it, relative to the model

swift crag
#

Note that there is a small "skin" that extends past the visible collider

#

so you might need to move its center a little higher than you think

lapis veldt
steep rose
#

if it is touching the ground how you would like then sure

lapis veldt
#

I am still new with using character controller, but is there a way to "snap" the character to the ground or something?

steep rose
#

IK could do that

frail hawk
#

or a simple raycast

swift crag
#

move the character down super far

#

...that might cause you slide off to the side, actually

wintry quarry
#

I'm pretty sure they're talking about the visuals matching perfectly with the collider

swift crag
#

ah, true. clarify pls

steep rose
#

if they want no feet sliding, IK could do that

lapis veldt
swift crag
#

oh, yeah, when moving things around in the scene view?

wintry quarry
steep rose
swift crag
#

inverse kinematics would be appropriate for making the feet rest firmly on the ground

steep rose
#

there is a snap function for scene view

#

yup

swift crag
#

Also, if you hold shift + ctrl while moving an object, it will snap onto colliders

#

This may be what you're thinking of

steep rose
#

if you want a runtime snap, you could use a raycast like murado said or just stick the feet to the ground using IK

lapis veldt
#

but IK isn't used with rigidbody?

swift crag
#

inverse kinematics is an animation thing

steep rose
#

IK has no connection to RB or CC

lapis veldt
#

oh, I see

swift crag
#

also, see how the behavior varies when using "Center" mode vs. "Pivot" mode. I just noticed that it matters!

lapis veldt
#

now back to remaking the animations work again xD

#

also, does this allways appear because I have both the old and new input system enabled in the project?

swift crag
#

No, that is unrelated.

#

It is one hell of a legacy warning though

#

a long time ago, back when giants roamed the earth, Component had some properties on it like camera and rigidbody

#

basically equivalent to calling GetComponent

#

These properties were deprecated ages ago and don't work in builds anymore

#

But they still exist in the editor, so you still get warnings when you declare a member with the same name

lapis veldt
#

ah, I see

swift crag
#

You can tell the compiler you meant to do this by adding the new keyword. But I'm pretty sure this then causes complaints during builds (because the properties don't exist in a build)

#

I was kind of hoping they'd make the enormous breaking change of deleting these damn things in Unity 6

#

ah well

lapis veldt
#
[SerializeField] private Transform camera;

that's the line

swift crag
#

I either use another name or ignore the warning

#

also you're going to be told to use Cinemachine in about...3 seconds

#

😄

#

(it's cool, use it!)

steep rose
#

Cinemachine is better

#

it is just a factual statement

swift crag
#

the developers have added features I pined for on the cinemachine forum

lapis veldt
#

yeah, I want to use cinemachine, but either I am not good enough or I am doing something wrong sometimes

#

especially when I want to use freelook

long jacinth
#

i cant make a function in a function right

lapis veldt
#

welp, I changed back to cinemachine and somehow I got it right

#

like the freelook is working as I want now

minor dagger
#

how to remove black from trees

lapis veldt
#

isn't that a texture error?

minor dagger
#

idk

languid spire
#

certainly not a code problem

minor dagger
#

oh you think

languid spire
#

no, I know. So why post in a code channel

minor dagger
#

where should i post it

steep rose
polar acorn
minor dagger
#

yeah i did it thx

rancid tinsel
#

is there some better way of handling UI references to a DDOL script? it was causing issues for me so I just disabled DDOL and put the script in both scenes and manually assigned it, but I feel like there is something better I could do

swift crag
#

Is this a singleton? If this DDOL'd component always exists (and there is never more than one of it), then adding a way to statically access it would be fine

#

for example, I have a GameController component that bootstraps the game and is responsible for switching between modes (title screen, main menu, gameplay)

#

It lives in DontDestroyOnLoad forever

timber tide
#

dont reference it directly, just reference it by the static class call

#

you may need to change execution ordering if it is spawned in the same scene though

#

You can also handle execution ordering by having a load scene and throwing all your DDOL managers onto that

swift crag
rancid tinsel
rancid tinsel
#

I didn't consider that

timber tide
#

project settings there's an execution ordering tab

swift crag
#

That would not affect your ability to store a reference to the DDOL'd component

#

you won't be able to serialize references to whatever this thing is

rancid tinsel
#

would I have to assign the buttons in awake/start when the scene is first loaded then?

swift crag
#

Explain what you're actually doing here. What is this DDOL'd object?

rancid tinsel
#

similar to yours, a SceneManager of sorts - loads scenes, reloads current scene

swift crag
#

okay, so you have some UI that lives in individual game scenes and that needs to be able to talk to the SceneManager

rancid tinsel
#

yes (play button for instance)

swift crag
#

Create a new component and put it on the UI object

#

Have the buttons call methods on this component

#

and then have that component find the scene manager and call whatever methods are needed on it

rancid tinsel
#

by component you mean a new script right?

swift crag
#

a new script file that contains a class that inherits from MonoBehaviour

#

that's how you define a new kind of component

rancid tinsel
#

ah okay i think i understand what you mean now

swift crag
#

(i don't like to use "script" for anything but the actual script files)

rancid tinsel
#

Button > NewComponent > find SceneManager

rancid tinsel
swift crag
#

This avoids needing any direct references between the UI and your SceneManager object

rancid tinsel
#

that makes sense, ill implement that

#

thank you

clever idol
#

Im working on a 2d game. When i shoot (right click) there come a bullet and it does damage and all but the speed is the problem. If click close to the firepoint the bullet goes slower then when i click futher away. Anyone knows how to fix this? (i want them to go the same speed reguardless of the distance of where you click)

swift crag
#

Sounds like you're doing something like this

#
Vector2 shootDir = clickPoint - playerPosition;
bullet.velocity = shootDir;
clever idol
#

The code has too many characters to past here but i can send a ss of what i currently have

swift crag
#

okay, so you correctly normalize that vector before using it

#

Ah, but there is one issue

#

You do these two things:

#
  • Normalize the vector
  • Set the Z component to zero
#

What if the Z component was very large? That means most of the vector's length is pointing in the Z direction

#

So when you normalize it and then remove that Z component, the resulting vector is very short

clever idol
#

ok so...?

#

can you tell me how i could fix this?

swift crag
#

you want direction to have a length of 1

#

but you're normalizing it before you get rid of the Z component, so the length is no longer 1

clever idol
#

Ok thanks ill try that

swift crag
#

you'll try what?

clever idol
#

im very confused rn

#

i changed the diraction.z = 1;

swift crag
#

wel that's going to be even worse

#

now the bullets are shooting into the screen

clever idol
#

Bruhh i have no idea what im doing rn so... plz help

swift crag
#

(well, actually, nothing will really change -- the Z component gets thrown out when you set the velocity)

clever idol
#

void Shoot()
    {
        // Bereken de richting van de muis naar het afvuurpunt
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3 direction = (mousePos - firePoint.position).normalized;  
        direction.z = 0;

for (int i = 0; i < numberOfPellets; i++)
        {

float spread = Random.Range(-spreadAngle, spreadAngle);

Vector3 spreadDirection = Quaternion.Euler(0, 0, spread) * direction;

GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);

Rigidbody2D bulletRb = bullet.GetComponent<Rigidbody2D>();

bulletRb.velocity = spreadDirection * shotSpeed;

BulletScript bulletScript = bullet.GetComponent<BulletScript>();
            bulletScript.maxReach = maxReach;  
            bulletScript.damage = damage;    
        }
    }
}

#

idk what to do at this point

swift crag
#

stop and think about what these two steps are doing

#

let's break it down into three steps...

Vector3 direction = (mousePos - firePoint.position);
direction = direction.normalized;
normalized.z = 0;
clever idol
#

ok yes

swift crag
#

tell me what each of these steps does

clever idol
#

it calculates where to shoot and normalizes the diractoin?

swift crag
#

no, I want you to explain what each line is doing and why it's there

clever idol
#

Vector3 direction = (mousePos - firePoint.position);
calculates the direction from the firePoint to the mouse position

direction = direction.normalized;
normalizes the direction vector so it does something idk bout that accutally just found it online

eternal falconBOT
swift crag
#

right now it's just a magic incantation

#

and it's not working!

#

see the link dec_ves posted

clever idol
#

ye ik its not working but idk how to fix it

swift crag
#

because you don't know why you're doing it

#

A vector has a direction (where it's pointing) and a magnitude (how far it goes).

#
Vector3 shootVec = new Vector3(100, 0, 0);

This vector points to the right and has a magnitude of 100.

#

If I set my bullet's velocity to shootVec, it would start flying at 100 meters per second to the right.

clever idol
#

ok ye i understand

swift crag
#

So if you just used shootVec without any further work, your bullets would fly twice as fast if you clicked twice as far away.

#

That's obviously wrong.

steep rose
#

so normalization helps with this

#

by keeping the same direction whilst making the magnitude 1, which then can be multiplied using the fundamentals of multiplication

clever idol
#

ye i tried but apperenlty i did it wrong ig

swift crag
#
Vector3 shootVec = mousePos - firePoint.position;

Vector3 vec1 = shootVec * 10;
Vector3 vec2 = shootVec.normalized * 10;

The magnitude of vec1 depends on how far apart the two points are.
The magnitude of vec2 is always exactly 10

#

So that's why we normalize here. We only care about a direction between two points. We don't care about how far apart the two points are.

clever idol
#

yes

swift crag
#

But there's a second problem -- mousePos and firePoint.position can have different Z components.

#

mousePos is probably at Z=-10 or something, where the camera is located

clever idol
#

frick... yes

swift crag
#
Vector3 shootVec = new Vector3(1, 1, -10);

If you normalize this vector, its X and Y values are going to be very small

#

The vector barely points in the X or Y directions.

#

It mostly just points in the -Z direction

#

Therefore...

#
Vector3 shootVec = new Vector3(1, 1, -10); // magnitude is a little more than 10
shootVec = shootVec.normalized; // magnitude is now 1
shootVec.z = 0; // magnitude is now almost 0
#

That's your problem.

clever idol
#

ok i kinda understand now

#

ok i understand what you just explained but... what do i need to remove and add to my code?

swift crag
#

here's a visual example. this vector mostly points straight up -- if I then get rid of the up-and-down part, the resulting vector is much shorter!

clever idol
#

yeye i understood that part and all

swift crag
#

so what should I do if I don't care about a vector's magnitude, and just want a direction..?

clever idol
#

remove the vectors magnitude?

swift crag
#

which you can do by...

clever idol
#

idk just plz help, i dont need a whole explaination rn

polar acorn
swift crag
clever idol
#

i feel really stupid rn ):

steep rose
#

scroll up

clever idol
#

im new to coding alr go easy on me plz

polar acorn
clever idol
#

what if i just use a vector2 instead of vector3?

polar acorn
#

Vector2s still have direction and magnitude

swift crag
#

you might accidentally solve the problem by doing that

#

again: the problem is that, after doing this:

shootVec.z = 0;

shootVec's magnitude is no longer 1

#

but we want it to be exactly 1, so that we get a consistent speed for our bullet

clever idol
#

ye i mean i understand that whole think about magnitude but idk how to apply it

steep rose
#

you already did it

clever idol
#

i havent changed my code since the start of this conversaion

steep rose
#

look at your code

#

what there makes the magnitude of a vector 1 whilst keeping the direction

polar acorn
#

Hint: You just got an extensive explanation as to what this function does

clever idol
#

MAN idk ):

#

i feel stupid and real sad cuz you guys are trying to help me so hard

polar acorn
#

So, what was the name of the function Fen was explaining earlier?

clever idol
#

normalized

#

ig

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

swift crag
# clever idol normalized

Correct. shootVec.normalized gives you a vector that points in the same direction as shootVec, but with a magnitude of exactly 1.

#

let me provide a more obvious example

#
shootVec = // whatever
shootVec = shootVec.normalized;
shootVec.z = 999999999;
#

shootVec's magnitude is now...not 1

#

it needs to be normalized again.

#

coming back to the sensible example:

shootVec = // whatever
shootVec = shootVec.normalized;
shootVec.z = 0;
shootVec = shootVec.normalized;

now we have a vector that:

  • only points in the X and Y directions
  • has a length of exactly 1
#

The first normalization is pointless -- we don't care about the value of shootVec after normalizing it the first time -- so it can be removed

clever idol
#

ye

#

how about this...

#

can you change my code pls and we are both happy

swift crag
#

well, given that I directly gave you the correct code, I'd think you're there already..

clever idol
#

bruh ):

tender breach
tender breach
#

I know, but people in other servers weren't saying anything.

swift crag
#

okay, but this is still a Unity server

polar acorn
#

This looks like web-page javascript, which is not known for having any sort of physics engine

cosmic dagger
somber nimbus
#

Hey! I got these venom thingies in my game and I want to do two things: First, make a checkpoint in the level in a certain point and second, when colliding with the venom, it sends you to that checkpoint. I'm a beginner to coding and I don't know how to do this, would appreciate some help/guidance!

#

I don't have a life or HP system neither do I want to place one. Just like... it transports you to the checkpoint. Like you have to avoid it to progress

#

That's my design logic

frosty hound
timber tide
#

because you can use that same concept to say, add flags (checkpoints) throughout your level which if you come into contact with will flag your most previous location

#

Actually, if you have the venom/death logic working already then you should probably have an idea how to do contacts

somber nimbus
timber tide
#

How about a GameManager and using singletons? That would make this pretty quick

somber nimbus
#

What is a singleton, if I may ask?

timber tide
#

They're (semi) static classes that can live on the scene

#

but two ways I would resolve this:

  1. Do it similar to the coins such that if you come into contact with a check point, then update the player's last known checkpoint location on the character itself (much like incrementing your coin counter)
  2. Instead of writing that value on the character instance, communicate to the GameManager and set it there
somber nimbus
#

Oooh okay, I'm starting to get it now!

#

I think the second one is a bit more viable for me at the moment

#

Thank you so much for helping me understand!

compact dirge
#

https://paste.myst.rs/t3xh2zap
guys i'm a bit confused. Why the game stops until the coroutine is ended? I can't see the movement, it's just like a teleport as now....

timber tide
compact dirge
#

oh yeah it worked!

timber tide
#

yeah, careful working with while loops

brittle isle
#

Mario-like swimming help, ad general control issues

rich adder
#

how can we possible know that without looking at the code / setup

#

if you're not using transitions then you have to better match how you switch back to the idle clip

slim lark
astral falcon
final sluice
#

Is it good to put every reference slot to public, like "public rigidbody2D rb" instead of private ? Is there a point to make a reference private ?

astral falcon
teal viper
final sluice
naive pawn
#

encapsulation makes separation of concerns clearer, and prevents accidental external modification

teal viper
final sluice
gilded canyon
teal viper
# final sluice Sorry but I don't see how it's applied in coding

Well, here's a better analogy. Imagine scripts being departments in a huge company or factory. You don't want people from other departments to enter freely in your department and interfere with your work, do you? Scripts(or classes) are these separate departments. They all do their own thing and only cooperate with each other using the official channels and rules.

languid spire
teal viper
#

By making a field public, you're basically allowing anyone to get in there and do with it whatever they want.

languid spire
gilded canyon
#

ok

final sluice
#

I saw some people use m_name instead of just name when assign variables, is there a reason to this ?

#

like int m_score instead of int score;

languid spire
#

old C and C++ code convention

teal viper
languid spire
#

these things are from pre IDE days and totally irrelevant today

teal viper
#

It depends on the conventions in your project or company. There are many that still conform to them. Especially in C++

eternal needle
# final sluice Is there a reason to make things unaccessible ?

One very important thing to realize here: these are all for the developers to make the development process smoother. Private/public is your way of denoting what values are allowed to be edited externally to the script. There is no change in the actual game logic or what the user sees when playing the game.
What you were told above by others is correct but I cant imagine youd really understand the terms used or analogies much as a beginner. It's something you'll start to understand more with time. A lot of the time, you dont want other scripts to be able to edit the variables

final sluice
devout flume
#

It's also useful to do that because you know that whenever you type m_, you'll get every field you're looking for. Your IDE won't show you any gibberish in the list of symbols it will prompt you

#

Probably nowadays indeed

fleet onyx
#

hello, since I'm trying everything possible, I would like to know if I wrote this wrong. For who doesn't know the issue I'm facing, since I updated from Unity 6000.0.24f1 to 6000.0.30f1, I got into Safe Mode and got these errors. In the 24f1 version, these are not counted as errors, but here these are. Also, today I noticed that other scripts (like the one that manages the player) are like disabled? (in Inspector, they are signed as (Script) and have less opacity, they doesn't even show the public values I used to change).

This is one of the errors that the Unity console displays:

Asets\Scripts\GameManager.cs(22,12): error CS0246: The type or namespace name 'TextMeshProUGUI' csould not be found (are you missing a using directive or an assembly reference?)

Assets\Scripts\AudioManager.cs(11,12): error CS0246: The type or namespace name 'Button' could not be found (are you missing a using directive or an assembly reference?)

long jacinth
#

how do i add an onclick object and function through script

burnt vapor
fleet onyx
#

thanks, but I've already done this, I've tried even deleting these and the upm folder and regenerate the project

#

there aren't even new updates of packages

#

in package manager everything seems fine too

languid spire
#

you can see TMPro is underlined. In VS open the solution Explorer. then open the References section of Assembly-CSharp and screenshot that

long jacinth
verbal dome
long jacinth
real thunder
#

so I decided to make a sync rotation animation and it kinda work but kinda not

#

transform.localRotation = Quaternion.Lerp(Quaternion.Euler(0, 0, 0), Quaternion.Euler(0, 360, 0), Mathf.Repeat(Time.unscaledTime * lootSpinSpeed, 1));

#

I can make it work by making it two lerps

#

the question I want to ask if there are better ways to do that

#

or should I even do that or making a "rotation manager" object with a list of stuff to rotate is a better idea

#

I guess there is also a way to make it a shader? but I... hesitate to touch shaders

languid spire
# fleet onyx

So there is obviously a problem with your .csproj file.
Close your project and in the project folder delete the .sln and .csproj files. then open the project to regenerate them

fleet onyx
#

ok I'll try thank you

#

ok so problem is still here sadly. I also noticed that in package manager, if I try to search textmeshpro in registry, it doesn't show up

languid spire
#

can you post the contents of the Assembly-CSharp.csproj to a paste site

fleet onyx
#

sure

bitter apex
#

Is there any way to make an array vary in length depending on a number of inputs, for example? In c# you have to define the length of the array, but I come from python where you don't have to define the length of the array beforehand, and the length of the array changes automatically.

languid spire
bitter apex
#

thanks a lot dude

fleet onyx
#

uhm... which website can I use to share it? Or can I just send the .csproj file here?

eternal falconBOT
languid spire
#

ignore gdl.space

fleet onyx
#

yeah I used second one, thank you

final sluice
#

Say I want my obstacles to disappear after reaching a location, is OnTriggerEnter or an if (reaching position) { Destroy()} in Update better in terms of terms of optimization ?

#

Also is collision detection has its own interval or it runs with fixedUpdate ?

real thunder
#

it should happen within FixedUpdate loop

real thunder
languid spire
fleet onyx
#

yes it does exist

#

do I share this too?

languid spire
#

nah

#

I do see one problem although I have no idea how to fix it
the project has this
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
targeting .NetFrameWork 4.7.1 but all of the references are targeting .Net Standard 2.1

fleet onyx
#

that's weird, in Player settings I did change it to .Net Standard 2.1

rich adder
#

Destroying object doesn't matter where you do it, the important worry would be Instantiate and Destroying the same objects. That creates constant garbage

fleet onyx
#

btw so, is this a visual studio issue? Maybe triyng to remove it from external tools and adding it again fixes the issue?

real thunder
real thunder
#

it's about how cost efficeint keeping a trigger collider on the scene vs doing update distance checks

rich adder
idle obsidian
#

Where can I get nametag?

rich adder
real thunder
idle obsidian
#

Unity Nametags

rich adder
swift crag
# idle obsidian

i mean, you can create a text object and staple it to an object...

#

this is a very confusing question

verbal dome
#

My troll detector is tingling a bit but it's not certain

rich adder
#

is this roblox ? i'm confused what are we looking at

idle obsidian
#

Where is products? This is Unity Systems profucts?

real thunder
rich adder
rich adder
idle obsidian
#

wtch

real thunder
swift crag
rich adder
verbal dome
#

How many of these objects are we talking? @real thunder

swift crag
#

The physics system will do a better job of keeping track of lots of objects that can all collide with each other

real thunder
rich adder
verbal dome
real thunder
#

I am getting curious myself

verbal dome
#

I'm also gonna guess that using a squared distance check would be faster

#

If it's just one object or a few objects then I wouldn't even bother thinking about it

#

If it's several, I would probably profile it

real thunder
rich adder
#

if it already got rigidbody id stay stick to the trigger msgs since you already have the cost of rb / physics running in the physics scene

real thunder
#

alright sorry for bumping but

#

how would you make a synced rotation animation for random coins and such?

rich adder
#

you want all coins sync

#

use a main script/object to loop through all coins for rotation ? or are u asking something else

swift crag
#

Explain what you're actually trying to accomplish

#

Oh, I get it

#

I was overcomplicating it in my head :p

#

All you need to do is ensure that each coin is at the same rotation at the same time. Consider something like this...

#
void Update() {
  transform.rotation = Quaternion.AngleAxis(Time.time * 45, Vector3.up);
}
#

Everything that has this component on it will have the same rotation at the same time.

#

since they're directly computing a rotation from the current time

#

(instead of, say, doing...)

verbal dome
rich adder
#

putting an Update loop in each coin tho 😬

swift crag
#
transform.rotation *= Quaternion.AngleAxis(45 * Time.deltaTime, Vector3.up);
real thunder
swift crag
#

If you want to be really clever, do it in the vertex shader 😉

rich adder
#

if you have 200 coins now you got 200 calls into the C++ backend which may not be ideal, I usually mass rotate them with 1 script. Blogpost from unity left me scarred

swift crag
#

or what happens every time you access any Unity property

rich adder
#

I'd like to know 😛

verbal dome
swift crag
real thunder
#

yeah I stated in the start that I am aware of the option of making a shader or a rotation manager object doing that

swift crag
verbal dome
#

Most of the common unity object properties are C++ side

swift crag
#

[sound of a car crash]

rich adder
#

yeah but isn't Update loop more "heavy" or am misunderstanding the unity blog post i read?

#

I'd be glad to know I worried for no reason xD

swift crag
real thunder
#

well I have heard that each update call eats some performance even if it's empty

rich adder
#

correct

swift crag
#

it still has to invoke the method

pallid nymph
#

I think the Update thing may be outdated... I had a much higher number of updates than that, switched to doing it in single Update and it had close to 0 impact (think 2k objects)

real thunder
#

the other option would be to make a manager with a list where I put and remove coins from each time tho (no, I am lazy making it pooled)

#

would it be much better

rich adder
real thunder
#

honestly I don't really care about small overheads

rich adder
#

small things add up, thats the thing

real thunder
#

yeah but I am making a small shitty game where it's not much things which may be adding up...

hexed terrace
rich adder
#

but yeah never let creativity / progress suffer because of pre-mature optimizations

pallid nymph
swift crag
#

You should do whatever makes the most sense to you first

#

so that your game doesn't make you want to die

verbal dome
#

I get the whole "premature optimization" thing but I also like to do things right from the get go so that I don't have 1000 small things to optimize later on when they start adding up

real thunder
#

I have watched a vid where a dud was like hey lets super optimize your game and make all updates be called by one god entity and make sure to add methods there spawning things and removing despawning things

real thunder
#

and... that does not make many sense

swift crag
#

Now, I actually do something a lot like this in my game

#

But this is because I want to have explicit control over exactly which order things run in

rich adder
#

making your own Tick is also viable.

swift crag
#

my entities have modules, and modules can have child modules

#

the entity ticks all of its modules that don't have parents, and then those modules tick their children

real thunder
verbal dome
#

I use that module pattern so much in my games

#

Ended up making a snippet for it in VSCode

rich adder
# rich adder https://unity.com/blog/games/optimize-your-mobile-game-performance-tips-on-profi...

Minimize code that runs every frame
Consider whether code must run every frame. Move unnecessary logic out of Update, LateUpdate, and FixedUpdate. These event functions are convenient places to put code that must update every frame, while extracting any logic that does not need to update with that frequency. Whenever possible, only execute logic when things change.
If you do need to use Update, consider running the code every n frames. This is one way to apply time slicing, a common technique of distributing a heavy workload across multiple frames. In this example, we run the ExampleExpensiveFunction once every three frames:

swift crag
#

we've got so many kinds of ticks!

real thunder
#

speaking of the profiler most if not all lag I ever saw are caused either by rendering or animation

pallid nymph
swift crag
rich adder
swift crag
#

the #1 performance killer is YOU NEVER FINISH YOUR GAME

verbal dome
swift crag
#

not me, spending all of yesterday trying a redesign that turned out to make no sense

real thunder
verbal dome
swift crag
#

lmao

rich adder
#

brek it

swift crag
#

I...don't remember why I didn't just make Teardown public. That's how Init works.

pallid nymph
swift crag
#

Oh, I think I was planning to make sure the teardown is valid before calling Teardown

#

(e.g. no double-teardown)

#

Making PerformTeardown non-virtual ensures that this behavior is kept by all modules

#

maybe

#

i forgor

real thunder
#

by the way at some point I realized that if at the same frame alot of collisions or other stuff happened, I might be wanting to first check what happened overall and only then react
does that makes sense?
like I am getting all OnCollisionEnter thingies making events out of them and each fixedupdate if there are any I run through them first and then react to each
does that makes sense?

#

not event events, I mean I making structs

#

which are kidna like events to handle

swift crag
#

I guess that could be useful if you want to, say, spawn no more than 10 particle effects at once

#

(and also not just spawn them on the first 10 collisions)

#

Oh yeah, I have done something like that. I gathered a big list of all possible places to play a sound, and then randomly picked a few to play one shots from

real thunder
#

I did that to configure the ragdoll of dying enemies properly

verbal dome
#

And at that point it's basically random, based on execution order

#

Or are you talking bout something else

real thunder
#

I ve heard valve made it consistenly that the player who joined last is the one who dies this situation

#

somehow

verbal dome
#

That makes sense from the programming perspective, the player was added to the player list last so its shooting logic gets ran last

real thunder
#

I did that to let's say I have raycast shooting shotgun and it killed the enemy where 7 pellets killx and 3 are overkill

#

and I want to properly give a ragdoll the dying impulse

#

if it was independent bullets that would be kinda... lame and inconsistent

#

but each LateUpdate enemy checks all hits he took and if he is dying he goes through all of them again to get the impulse

verbal dome
#

That reminds me, I gotta do some special logic for my shotgun pellets. No point in playing 8 sounds and 8 blood particles at once if they hit the same spot...

real thunder
#

I didn't figure out anything better than making each hit play a sound but more quiet ><

verbal dome
#

Gonna probably give them some shared ID and add some distance checks to avoid too much clutter

real thunder
#

yeah I should ve do something like that

verbal dome
#

And that parameter controls the audio in FMOD and the scale of the VFX and bullet decals

real thunder
#

is that a fps? do you have bulletholes?

#

yeah you got them

verbal dome
#

Yeah, just edited that in

real thunder
#

how do you orient them?

verbal dome
#

Basic stuff, raycast hit's normal

real thunder
#

but what about edgecases

verbal dome
#

Like what?

#

I might have handled some but can't remember off the top of my head

real thunder
#

like literally hitting an edge

verbal dome
#

Not sure if i handle that case atm

#

It could be fixed by using spherecasts to get a more smoothed normal

#

But that feels a bit expensive

#

Maybe I could do it for hits closer to cam

real thunder
#

I have spent several days making a code which shoots like 12 raycasts out of the hit point to feel the geometry and accordingly turn the decal

verbal dome
#

Maybe try a single spherecast instead? It should give decent normals on sharp edges

real thunder
#

I will look into it next time I make fps

verbal dome
#

Like hitting a corner like this should give you an average normal (yellow)

#

I guess this is the issue you are talking about?

real thunder
#

I wonder why did I never find anything about spherecasting while googling how to properly orient a decal

#

this is one of the cases, yes

#

worst case is hitting a corner

verbal dome
#

True

real thunder
#

or a.. reversed corner let's say

verbal dome
#

Apparently I am just relying on the angle fade on the decal to basically just hide decals at bad angles

#

Just fades out towards the corner

real thunder
#

yeah I also didn't knew I could do that or there were no such thing on URP decal

#

also urp decals are really horrible in terms of making them pooled

rich adder
#

they have GPU instancing, they are pretty performant already

real thunder
#

by experimenting I found out that the only no alloc way to hide them seemed to be manually setting their size to 0 0

#

neither scaling to zero or disabling them worked iirc

verbal dome
#

Hmm.. I gotta investigate if HDRP decals have that issue. Never really thought of it

real thunder
#

it shoots raycasts to the sides and then either forward or backwards to feel where the bullet hit

verbal dome
#

And you get the average normal from that?

real thunder
#

yeah

#

I failed to google up any kind of proper solution

#

so I did this

swift crag
#

You could fire a few raycasts and look at how quickly the normals are changing

#

If the change is dramatic, then do a spherecast or perform more raycasts to get a better average normal

#

kind of like looking at ddx in a shader

real thunder
#

wish I knew anything about shaders

#

well more than sheer basics

#

at this point this place seems to me the pinnacle of getting info about making the game out of all

swift crag
#

bless bgolus

#

every weird shader question I have is invariably answered by bgolus

real thunder
#

wonder if it is

swift crag
#

so ddx(i.normal) tells you how quickly the normal is changing across pixels, for example

#

very nifty

real thunder
#

unity discussions are not looking very helpful if your question is not trivial, same for google

swift crag
#

which takes me to a Unity Forums link, which redirects me to Discussions

real thunder
#

it's complicated, googling most stuff giving me a proper answer, sometimes, however...

#

sometimes there are alot of answers about something close to my problem but not quite and I can't find stuff about the exact thing
sometimes there is almost nothing and if I ask on forums there are dozens of views but zero answers for weeks and eternity presumably

hexed terrace
#

You often likely to be unable to find solutions for the exact thing you're looking for. What you need to get good at is find things close and extrapolating from there how to sort your thing out

real thunder
#

yeah I did this raycast thingie but if I knew about spherecast...

hexed terrace
#

read the docs

#

Reading the docs for raycast would take you to Physics.Raycast -> Physics is a link -> click and read the other properties/ methods -> SphereCast is present

swift crag
#

at some point you just gotta' thumb through the manual, yeah

#

sometimes I just look at random autocomplete suggestions from my IDE

real thunder
# hexed terrace read the docs

I don't think reading the docs would help me to get the idea how to orient decals
Like, I was aware that spherecast exists, but it was stated as
"This is useful when a Raycast does not give enough precision, because you want to find out if an object of a specific size, such as a character, will be able to move somewhere without colliding with anything on the way"

#

getting an average normal is not what I would expect from spherecast, I was expecting it to return the only one normal of the exact place it collides

verbal dome
#

I did some raycast/spherecast profiling and in a medium complexity scene spherecasts are around ~3x the cost of a single raycast

swift crag
#

i was profiling this at one point

#

i was trying using either a grid of raycasts or one spherecast

#

i wound up doing neither 💥

verbal dome
#

Found this tester thing i made some times ago

#

Idea was to find out when it becomes feasible to use RaycastCommands

#

I ended up testing NavMesh raycasts, spherecasts etc.

#

Turned out that NavMesh.Raycast is more expensive than I thought

swift crag
#

I use RaycastCommand for my vision system

#

all of my entities make requests to a vision system, and then it runs a big blob of raycasts

#

the results get sent out on the next frame

verbal dome
#

Same here, although I instantly complete the command, I should definitely give it a frame to complete

swift crag
#

You won't get full parallelism there

#

Anything that needs to change the physics scene will stall until the command completes

#

But it can still help

verbal dome
#

Yeah It's not optimal

swift crag
#

I wonder if I should wait to dispatch the command until rendering is happening...

verbal dome
#

Half of the implementation is missing

swift crag
#

Oh no it's Nitpicky Optimization Time

#

bring out the scene with 1000 "vision benchmarker" entities

swift crag
verbal dome
#

So not really a fair comparison :P

swift crag
#

oh hey, it might actually be completing in time

verbal dome
#

How many raycasts do you perform on average?

swift crag
#

i...removed the thing that tells me how many i'm performing here

#

hang on

#

So that's 833 raycasts

#

I threw 50 "vision benchmarker" entities into a room

#

each one is trying to look at all of the other entities

#

it's also timesliced so that only a third of the entities get vision updates per frame

#

Normally, each entity has several "vision targets", so there are more raycasts

#

it also shoots rays at light sources so that it can figure out how bright the environment around itself and its target is, but this scene has no realtime lights

#

also i'm doing 833 spherecasts for uh

#

why am i doing spherecasts

#

i thought i turned those off

verbal dome
#

Yeah I'm thinking of using the same raycastcommand batch for light checks too

#

Actually I could technically cramp most of my raycasts in the game into one command

swift crag
#

with gdl.space being broken i have no idea what to use here

#

!code

eternal falconBOT
swift crag
#

It's designed for physically accurate lighting in the HDRP

#

(i love having real light units. what the hell is "0.5 intensity"?)

real thunder
#

I haven't bother with mobs interacting with mobs but I can't wait to have the geometrically worsening performance

swift crag
#

yeag

long jacinth
#

Hello, is there a way so that each gameObject that accesses this prefab it has its own version of it and doesnt change it for the other gameObjects

like in this situation i have cities and they each access this building prefab and lets say upgrade its level i want it so that it upgrades for only one city and the others dont

swift crag
#

don't modify the prefab

cosmic dagger
long jacinth
#

and see if it works

cosmic dagger
#

instantiating the prefab will create a separate instance. that instance is a copy of the prefab; you can change what ever you want on it . . .

long jacinth
#

ok thank you

solemn fractal
#

Hi friends, how are you? I have an issue with my Scriptable object and not being able to fix it for some time. Basically I created a small system to spawn enemies and create waves in a mora controllable way to change it on the inspector. The problem here is that, if I change the number of waves from 1 to 100 for example, it works. but if I decide to change lets imagine wave 10 or any wave removing enemies or changing even the prefabs of the enemy that will spawn, sometimes it mess up. and during the game its spawned less or more and when spawed more the object sopawned is not recognized by the player to shoot. Shouldnt it update or save automatically when I do changes there? It only happens if after setting up the number of waves I try to add a new element to add a dif enemy in a random wave. Anyways it is not 100% that will bug but its often.. the thiong is if I have 1 wave and increase the amount to whatever number it works perfectly.. if I edit one of the waves it might woirk but sometimes dont.. like if it mess or dont save or. doesnt make sense.

long jacinth
#

how doesnt this work

swift crag
#

I have zero clue what CopiedBuildingTypes is

#

and you have not provided the error message

#

this makes it very hard to give you an answer

slim lark
rich adder
# long jacinth how doesnt this work

when you show a red squiggly line, at the very least show the error message that it says..
presumably InstantiatedBuilding is not same type asCopiedBuildingTypes contains (assuming thats even a list and not an array)

swift crag
#

hmm, i'm trying to use this shader in a Projector and i'm getting weird results

#

the projected image is appearing on every single object that the projector hits like this

#

(i threw this into a VRChat project, so this is Unity 2022.3.22f1)

slim lark
#

Yeah same thing on mine

#

It's just overriding the texture of anything it touches

#

my floor is a single massively stretched out crosshair lmao

swift crag
#

I think the projector is failing to set the necessary properties on the material

#

The shader is suppoesd to use a matrix in a property called _Projector

#

but if I remove that line, the result is identical

slim lark
#

welp

#

how do people do stuff like this then on newer unity? Do they ONLY use URP?

swift crag
#

As an alternative, you could just use a light with a cookie

#

Projectors let you do more complex blending (e.g. darkening a surface)

#

If you're fine with just making the surface brighter, create a spotlight and give it a cookie

slim lark
#

... I'm literally just projecting a laser light in the shape of a crosshair

swift crag
#

you'll need to set your cookie texture to clamp, not repeat

#

see the texture importer settings for that

#

(otherwise you get very wacky results)

slim lark
#

Perfect! That was so much easier, tyty.

polar acorn
swift crag
#

i'll have to remember that Projector just..doesn't project. huh.

#

I mostly do HDRP and URP, so I hadn't used it myself yet

slim lark
#

Well you're the one who finally managed to help me out so tysm

marble hemlock
#

okay i got a couple things working

  • i got an inventory system
  • i got an interact system

how would i go about a "quest" system?

long jacinth
marble hemlock
#

one that automatically updates?

swift crag
#

I need to see what you are actually doing.

pallid nymph
#

define a quest system 🤷‍♂️

polar acorn
polar acorn
#

It's a private list with no uses in this script so it might as well not exist

polar acorn
long jacinth
#

its an empty list that i want to add stuff to

polar acorn
#

It's not used anywhere

#

You don't add anything to it

marble hemlock
polar acorn
#

you never read it

#

it's a variable you've created and done nothing with

swift crag
#

you have deleted the line that tries to call Add on CopiedBuildingTypes

#

thus removing the error, I guess

marble hemlock
#

problem is, im not sure how to start

#

at first i was thinking a list but then it just sort of got more complicated than that
each quest would need their own script, i think

swift crag
polar acorn
swift crag
#

Displaying the quest can come later

polar acorn
#

Find similar things that all types of quests have

#

then find "Groups" of quests - fetch quests, slay quests, etc.

rich adder
polar acorn
#

and make classes representing them

long jacinth
swift crag
marble hemlock
#

i guess my question isnt exactly how to display it

long jacinth
polar acorn
#

In that case, @long jacinth , the answer is "You don't"

rich adder
polar acorn
long jacinth
#

ok thank you now it works

swift crag
rich adder
#

to avoid confusion you should really be storing these as their type not Gameobject @long jacinth

marble hemlock
#

i have nothing to display yet. im trying to figure out how would i go about creating a list of objectives, but each objective works different
like lets say i want the player to click 3 buttons (which would be its own quest)
collect some objects (quest)
and then i need them to click a switch (its own quest)

swift crag
#

and yes -- referencing everything as a GameObject makes it really hard to understand what is going on

marble hemlock
#

like each thing would have its own logic, so i feel like each would have its own script

swift crag
long jacinth
#

when instantiated it and added it to the list that means other gameObjects with the same script will have their own copy of the prefab right

marble hemlock
rich adder
#

each gameobject in the list would be their own instance (with their own stats)

marble hemlock
#

thats the bit thats getting me the most here

swift crag
#

I only have a few kinds of objectives. For example, SingleObjective is either:

  • Pending
  • Succeeded
  • Failed

If I want to tell the player to pull a lever, I give them a SingleObjective, then make the lever set that objective's state to "Succeeded" when the interaction ends.

#

I also have "combo objectives", which are just many objectives that all must succeed for the combo objective to succeed

#

So I'm keeping the actual game logic out of the objectives. The objectives are pretty much just checkboxes

marble hemlock
#

i didnt think this bit would actually just stump me

#

i think im sort of getting something here but i should probably write it down before i lose it

swift crag
#

Now, if you want things to happen as you reach various stages in a quest, you'll want to allow other parts of your game to listen to quest status changes

marble hemlock
swift crag
#

The fun part here is figuring out the references

#

One option is to have each quest be stored in a ScriptableObject asset. This makes it easy to reference the quest itself, but you'll also need to be able to reference a specific stage in the quest

#

e.g. "This door is open if stage 2 is complete"

#

Maybe you could make each quest stage an asset, too

#

So a quest would be a list of stages (which you might go through non-linearly)

marble hemlock
swift crag
marble hemlock
#

i need a pencil

swift crag
#

Note that I would avoid trying to store state -- that is, data that changes -- in these quest objects. These are just the definitions your game will look at

#

You might just have a class whose job is to remember the status of each quest and quest stage

#

That would make saving and loading reasonably easy

pallid nymph
#

My approach usually is... write down the different things I'll need, figure out the different implementations (even code them if necessary), figure out what's common and can be nicified

swift crag
marble hemlock
#

every quest is going to need its own bool isnt it

swift crag
#
Dictionary<Quest, bool> questsCompleted;
#

Serializing this so that you can save and load would require a little extra work

#

An easy approach would be to just do it by name, so you'd save out something like

#
{
  "Eat 3 Apples Quest": true,
  "Open Door Quest": false
}
#

the annoying part is that renaming a quest now breaks your saves

#

so my save files look more like

pallid nymph
#

I usually use the name as ID and have an idOverride param on these, so if I really wanna change the name, I can just type the old one as override

swift crag
#

yummy

#

oops self-dox

#

well, not really, but whatever. no file path for you!

pallid nymph
#

also, name is never used as DisplayName 😄

marble hemlock
#

i can feel my will draining

swift crag
#

Of course, you could also just hard-code everything if you want to

long jacinth
#

i cant do foreach() with a list right?

swift crag
#

Especially if you don't have grand aspirations to create dozens and dozens of quests

swift crag
long jacinth
#
foreach(GameObject i in CopiedBuildingTypes)
        {
            GameObject instantiatedButton = Instantiate(ButtonBuild, Spawn.transform.position, Quaternion.identity, Scroller.transform);

        }
#

"object reference not set to an instance"

swift crag
#

Perhaps Scroller is null, or Spawn is null, or CopiedBuildingTypes is null

polar acorn
long jacinth
swift crag
polar acorn
long jacinth
#

did i just instantiate stuff inside it

swift crag
#

Undertale is an incredibly popular game and it's implemented about as cleanly as a 23 car pileup

#

I'm building a very elaborate objective system that neatly integrates with my AI system (so that AI characters can turn objectives into goals, then compute plans to attain those goals)

#

but the player won't care if the game is bad

#

(or doesn't exist)

marble hemlock
swift crag
#

I've had the most fun making mildly janky games

#

god i need to do a game jam again

marble hemlock
#

i dont want to deal with the quest system but i know i cant avoid it forever

#

and i got this weird boost of motivation recently, and it was enough to get me to complete my inventory system in a way i liked, and just overall have an interacting system i liked

#

it will not last forever, and i should make use of it

swift crag
#

You can always replace the system later if you need to.

alpine fjord
#

A quest system would be great to have. But is it necessary?

pastel sleet
#

he i am a beginner with xr interaction toolkit. When i try to pick a object up it doesnt work. I use xr interaction toolkit

slim lark
#

Funky thing, when I use the spotlight it looks like this in the inspector, but in game it just spreads red light EVERYWHERE. Did I do something wrong when setting up the toggle on my button? Or did I mess up the code?

The button also only seems to work once or twice at most and then never again...

#

For reference, I'm using the built in render pipeline and using this with OpenXR

ivory bobcat
#

Put a log statement inside the function and see if it's occurring when expected. There's a possibility that the function is working but not as you're intending due to other stuff.

slim lark
#

The... function? I'm mostly concerned with the spotlight not rendering properly

#

like, in the editor it looks clean like that but in-game it's absolutely not. it's a chaotic red mess everywhere

ivory bobcat
#

I was concerned about your statement in regards to the button not working consistently.

slim lark
#

so it's just a problem with why is the spotlight a mess in game

polar acorn
#

!code

eternal falconBOT
halcyon shore
#
  using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class Movement : MonoBehaviour
{
    public Camera playerCamera;
    public float walkSpeed = 6f;
    public float runSpeed = 12f;
    public float jumpPower = 7f;
    public float gravity = 10f;
    public float lookSpeed = 2f;
    public float lookXLimit = 45f;
    public float defaultHeight = 2f;
    public float crouchHeight = 1f;
    public float crouchSpeed = 3f;

    private Vector3 moveDirection = Vector3.zero;
    private float rotationX = 0;
    private CharacterController characterController;

    private bool canMove = true;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 right = transform.TransformDirection(Vector3.right);

        bool isRunning = Input.GetKey(KeyCode.LeftShift);
        float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
        float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
        float movementDirectionY = moveDirection.y;
        moveDirection = (forward * curSpeedX) + (right * curSpeedY);

        if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
        {
            moveDirection.y = jumpPower;
        }
        else
        {
            moveDirection.y = movementDirectionY;
        }

        if (!characterController.isGrounded)
        {
            moveDirection.y -= gravity * Time.deltaTime;
        }

        if (Input.GetKey(KeyCode.C) && canMove)
        {
            characterController.height = crouchHeight;
            walkSpeed = crouchSpeed;
            runSpeed = crouchSpeed;

        }
        else
        {
            characterController.height = defaultHeight;
            walkSpeed = 6f;
            runSpeed = 12f;
        }

        characterController.Move(moveDirection * Time.deltaTime);

        if (canMove)
        {
            rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
            playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
            transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
        }
    }
}

why does it walk on its own?

long jacinth
#
Scroller = GameObject.Find("ButtonContainer");
        Spawn = GameObject.Find("Spawn");
        CityTabObj.SetActive(false);      
        foreach(GameObject building in BuildingTypes)
        {   
            GameObject InstantiatedBuilding = Instantiate(building);
            CopiedBuildingTypes.Add(InstantiatedBuilding);
        }
#

apparently copiedbuildingtypes is null

polar acorn
long jacinth
polar acorn
#

where do you actually create the list

long jacinth
#

at the top
List<GameObject> CopiedBuildingTypes;

serene barn
#

hello everyone good evening peter here i just have a quick question i am using oncollisionenter() function but everytime is collide with my player to the object that has a rb and a collider the function doesnt start only when i move to the side and my cube crosses the collider with one corner is there any who can help me so that it calls the function when I collide with the collider?

polar acorn
hot palm
#

do

List<GameObject> CopiedBuildingTypes = new();
polar acorn
long jacinth
long jacinth
alpine fjord
polar acorn
long jacinth
#

oh

hot palm
#

Short for

List<GameObject> list = new List<GameObject>();
bitter apex
#

how comes you can omit the end List<GameObject>(); ?

polar acorn
cosmic dagger
bitter apex
#

Yeah, I had a look and it's a c#9 feature for target-typed new expressions

cosmic dagger
#

per the example, the type is known on the left-hand side, therefore, it's not required on the right-hand side . . .

bitter apex
#

infers it from context

#

that's quite neat

hot palm
#

it is :D

drowsy socket
#

how do i make a custom rendering pipeline. i am pretty experienced in shader programming but i have never really used unity. i want to make a renderer for a black hole it needs to be ray marching based since i also want a volumetric for the accretion disc. it would be nice if someone could tell me how to make this possible and pass the necessary information to the shader. (GLSL if possible since i have more experience with that)

swift crag
bitter apex
#

rubs me the wrong way that you can define methods at a later point in your program than you call it

swift crag
slim lark
swift crag
#

I also noticed that the light can get into a sort of "bad state" when I changed the texture import settings. I had to remove and reassign the cookie to make it render properly again

wintry quarry
bitter apex
#

don't other c-based languages and ones like java (which are also compiled) require you to also define them before they're called? or at least by using forward declarations?

wintry quarry
#

not as far as I know.

bitter apex
#

i could be chatting out my ass tbf

swift crag
#

i'm more surprised that those languages don't allow it, tbh

bitter apex
#

i think it's really cool but it feels so bizarre

swift crag
#

It implies that you can't parse the language without knowing if a symbol exists or not

#

Well

#

Parsing C++ is a complete clusterfuck

#

so that makes sense

swift crag
long jacinth
#
        Spawn = GameObject.Find("Spawn");
        CityTabObj.SetActive(false);      
        List<GameObject> CopiedBuildingTypes = new();
        foreach(GameObject building in BuildingTypes)
        {   
            GameObject InstantiatedBuilding = Instantiate(building);
            CopiedBuildingTypes.Add(InstantiatedBuilding);
        }```
``` foreach(GameObject buildx in CopiedBuildingTypes)
        {
            GameObject instantiatedButton = Instantiate(ButtonBuild, Spawn.transform.position, Quaternion.identity, Scroller.transform);

        }```
#

idk why

#

but apparently the list is still not

polar acorn
#

Are both of these snippets in the same function

long jacinth
polar acorn
cosmic dagger
#

it's easier if you post a link to show all your !code. snippets don't help give us an idea of what our code does or where . . .

eternal falconBOT
long jacinth
#

second one in a function i made and first in start

polar acorn
long jacinth
polar acorn
long jacinth
polar acorn
# long jacinth

That's creating a variable in start. Where do you create the list you use in the other function?

long jacinth
#

"CopiedBuildingTypes"

polar acorn
#

That means when the start function ends, the variable ceases to exist

#

instead of creating a new variable, you should use the one you already have

long jacinth
polar acorn
long jacinth
polar acorn
long jacinth
#

but wont that remove things already in it if i do it agian

polar acorn
#

= means "Assign to". The variable CopiedBuildingTypes is a variable that can hold a list in it. Whenever you use =, you are changing the list that the variable holds.

wintry quarry
long jacinth
polar acorn
#

If you change which list the variable holds

long jacinth
#

wait

#

so CopiedBuilding types is a variable that holds a list

wintry quarry
#

It's a variable that references a list

long jacinth
#

wel where is the list

polar acorn
#

That's what the error is

long jacinth
#

oh

#

so i should create the list again right?

polar acorn
#

You can start by creating it at all

#

You aren't actually storing a list in your class variable anywhere

long jacinth
polar acorn
long jacinth
#

well i did that in the start function

polar acorn
long jacinth
#

then it gets lost because its the start function

polar acorn
#

You created a brand new variable, with the same name

#

You created a new variable in Start. You do nothing with the one you defined outside of Start

long jacinth
#

then how do i make it public

#

public void start() ?

polar acorn
#

Tell me, if you made a variable private int x = 3

Tell me, how would you change x to 7 in start?

polar acorn
#

Because that would be creating another variable

#

Now, look at what you put in Start for creating the list

#

Are you changing the value of CopiedBuildingTypes? Or are you making another variable with the same name

long jacinth
#

Oh I understood

polar acorn
long jacinth
#

I should have did CopiedBuildingTypes = new();

bitter apex
#

lordy lord

polar acorn
long jacinth
hybrid finch
#

i have an enemy follow player script which tells the enemy to follow player and i also have an enemy spawn script and im spawning in enemy prefabs, how do i set the player trasform(in the scene) to the script in my enemy prefab (in assets)

hybrid finch
wintry quarry
#

and then you asked for other ways

#

and I listed them

#

Is there one you wanted to know more about?

#

Ask clarifying questions if you don't understand

#

You're not going to get anywhere just reposting the same question.

hybrid finch
#

alr sorry

hybrid finch
wintry quarry
#

so ask questions

#

And I'm not sure how you can say you don't know how to implement it when i literally gave you a code example

#

If you didn't understand the example ask questions about the parts you don't understand

hybrid finch
wintry quarry
#

Send me the code of what

hybrid finch
#

spawn

wintry quarry
#

Was there something you didn't understand about the code example I shared?

hybrid finch
wintry quarry
hybrid finch
#

alr ill try 1 sec

#

ty

silent valley
#

!code

eternal falconBOT
silent valley
#

I'm trying to get the particle to act as a trail for my meteor. I want it to always move in the opposite direction to what the meteor moves in. My meteor also rotates and I want the particle system not to rotate. I'll share a video in a sec

rancid tinsel
#

why does this not work? i forgot

#

as in why can't i assign the scripts in the inspector

swift crag
#

What is a Rule?

rancid tinsel
#

a class

swift crag
#

show me how you have defined that class

rancid tinsel
swift crag
#

Okay, so it derives from MonoBehaviour

#

That makes it a kind of unity object, so that should serialize just fine

#

make sure that your code is actually saved and that you don't have any compile errors

rancid tinsel
#

it does serialize, just doesnt actually accept it

#

as if it was the wrong type

slender nymph
#

do you have any objects with that component attached in the scene?

polar acorn
rancid tinsel
#

no, is that required?

swift crag
#

well, yes

rancid tinsel
#

ah

swift crag
#

did you mean to refer to a prefab, perhaps?

swift crag
# rancid tinsel

the second screenshot shows a list of Rule objects in your scene

polar acorn
#

You should still be able to pull in a prefab

swift crag
#

It just won't show up in the "Assets" list, even if you have a prefab with a Rule attached to its root object

#

for Reasons (tm)

rancid tinsel
#

okay so id have to make a prefab for each of them got it

polar acorn
#

Each what?

rancid tinsel
#

each rule (inheritance)

polar acorn
#

If you don't have objects in the scene, and you don't have prefabs, what were you trying to add?

swift crag
#

i'm very confused by what you're doing now

rancid tinsel
#

the script 😭

swift crag
#

the script is a blob of text

polar acorn
#

It's a TextAsset containing a class

#

It doesn't exist until it's on an object

swift crag
#

Are you trying to refer to entire classes here, perhaps?

rancid tinsel
#

yeah now that you mention it that makes sense

swift crag
#

Explain what you're trying to actually do here

#

not your attempted solution: your original problem

rancid tinsel
#

i wanted to store the rules in an array, so they can be used to later validate an input from the player

#

each rule is its separate class as thats the best ive been able to come up with so far

supple wasp
#

Hi, I don't know if you can help me with this code. This code is supposed to make the YXZ axes appear when an object appears but it doesn't move it with the axes.

rancid tinsel
#

but they all inherit from Rule parent class

swift crag
#

Okay, so what you really want to do is create some classes like this

supple wasp
#

public class GizmoHandler : MonoBehaviour
{
    public enum Axis { X, Y, Z }
    public Axis axis;

    private Plane dragPlane;
    private Vector3 dragStartWorldPos;
    private bool isDragging;

    public void StartDragging(Vector3 hitPoint, Transform parentPiece)
    {
        // Crear el plano de arrastre basado en el eje seleccionado
        switch (axis)
        {
            case Axis.X:
                dragPlane = new Plane(Vector3.up, parentPiece.position);
                break;
            case Axis.Y:
                dragPlane = new Plane(Vector3.right, parentPiece.position);
                break;
            case Axis.Z:
                dragPlane = new Plane(Vector3.forward, parentPiece.position);
                break;
        }

        dragStartWorldPos = hitPoint;
        isDragging = true;
    }

    public void HandleDrag(Vector3 hitPoint, GameObject parentPiece)
    {
        if (!isDragging) return;

        Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
        if (dragPlane.Raycast(ray, out float enter))
        {
            Vector3 dragCurrentWorldPos = ray.GetPoint(enter);
            Vector3 dragDelta = dragCurrentWorldPos - dragStartWorldPos;

            // Mover la pieza y el gizmo
            switch (axis)
            {
                case Axis.X:
                    parentPiece.transform.position += new Vector3(dragDelta.x, 0, 0);
                    break;
                case Axis.Y:
                    parentPiece.transform.position += new Vector3(0, dragDelta.y, 0);
                    break;
                case Axis.Z:
                    parentPiece.transform.position += new Vector3(0, 0, dragDelta.z);
                    break;
            }

            dragStartWorldPos = dragCurrentWorldPos; // Actualizar el punto inicial para el siguiente frame
        }
    }

    public void StopDragging()
    {
        isDragging = false;
    }
}
#

If you can help me with this

swift crag
#
public abstract class Rule {
  public abstract bool Validate(string input);
}

public abstract class AllCapsRule : Rule {
  public override bool Validate(string input) {
    return input.IS_ALL_CAPS(); // i made that up
  }
}

public abstract class LengthLimitRule : Rule {
  public int limit = 10;

  public override bool Validate(string input) {
    return string.Length <= limit;
  }
}
#

These are not Unity objects. We're not going to attach these to game objects and put them in scenes

#

The immediate problem is that these things aren't serializable

#

That's an easy fix. Add [System.Serializable] to each class

rancid tinsel
#

This might be a dumb question but doesn't this break Single-responsibility principle? The project I'm making this for highly relies on SOLID principles for marks.

swift crag
#

We can now put a public LengthLimitRule foo; in a component and serialize an instance of LengthLimitRule

swift crag
#

it validates a string

#

i don't know how it could get any more single-responsibility than that

rancid tinsel
#

no but in my case it isn't a string I'm validating

#

ill show you what i mean

swift crag
#

oh, well, then replace string with whatever the user input is

#

same idea

rancid tinsel
#

idk if this changes it at all, but the rules are very different from eachother

polar acorn
#

Question: Why are the rules components? What objects are they going to be attached to?

rancid tinsel
swift crag
rancid tinsel
#

or i guess they are currently

rancid tinsel
swift crag
#

are you trying to validate English grammar

#

uh oh

rancid tinsel
#

kind of

#

to an extent

swift crag
#

so you have a sequence of sentence fragments and you have a few rules for how they're allowed to be arranged

rancid tinsel
#

its meant to just be good enough to ask some basic questions about a word that the player is meant to guess

rancid tinsel
#

im not sure if that impacts the structure you proposed

swift crag
#

okay so Rule validates a List<SentencePiece>

#

instead of a string

#

The commonality between every Rule is that they look at an attempted input and say "good" or "bad", correct?

rancid tinsel
#

something like that, the nodes are GameObjects and they're checked per rule whether they contain an IPrefix, IDescriptor or IValue

swift crag
swift crag
#

The larger problem with this is that, whilst you can do this:

[SerializeField] List<Rule> rules;

...Unity will only store the properties that are part of Rule. It won't remember any other properties.

#

it also won't let you pick which kind of Rule you want

#

There are several packages that solve this.

rancid tinsel
#

would i still be able to just brute force it with every rule and check if any returned false? since that was the plan originally

swift crag
#

Yes, that's trivial

swift crag
#

I have a list of "scorers"

#

I can pick the exact scorer I want and configure it

swift crag
#

and then you'd get to configure LengthLimitRule, if you picked that one

#

That solves the hard part. Now you just do something like

#
foreach (var rule in rules) {
  if (!rule.Validate(input)) {
    return false;
  }
}

return true;
rancid tinsel
#

ah okay that makes sense

swift crag
#
[SerializeField, SerializeReference, ReferenceDropdown] List<Rule> rules;
#
  • SerializeField so that it actually serializes this thing at all
  • SerializeReference to tell Unity to correctly store child classes
  • ReferenceDropdown to get the dropdown UI (that's the only part the package is providing)
rancid tinsel
#

would I still use that package if I'm hardcoding the rules? in my case I want the rules to just check things like if prefix is in position[0] etc

swift crag
#

The rules could be very simple

#

The point of the package is to let you pick which kind of Rule you want

#

Otherwise, you'd need a List<RuleOne>, a List<RuleTwo>, and so on and so forth

rancid tinsel
#

ah okay i see what you mean

swift crag
#

List<Rule> is what you want -- you don't care what the exact rules are

#

without SerializeReference, this gets saved wrongly, and with SerializeReference, you don't get an inspector UI for it!

#

hence the package

swift crag
spiral narwhal
#

I think I have a misconception about how I can update the parameter of a blend tree via script. I used:

    private static readonly int X = Animator.StringToHash("x");
    private static readonly int Y = Animator.StringToHash("y");

// ...

        _animator.SetInteger(X, (int)direction.x);
        _animator.SetInteger(Y, (int)direction.y);

But apparently this does not reach the blend tree? It only updates the animator's parameter, which I thought would then update the blend tree with the same name

rancid tinsel
#

ill take a look at it first thing tomorrow morning then since i feel like if i implemented a package rn id set everything on file lol