#💻┃code-beginner

1 messages · Page 25 of 1

true thorn
#

yep, I was actually looking for more details about this

somber wren
#

So i have a little spider that i'm trying to animate procedurally. But when it starts moving, the little targets are getting huge a offset on the Z axis. The spider still walks, but with the legs in this position.

I think its coming from the line 75 of this script : https://gdl.space/nogagabiki.cs
Because when i try to remove the offset, it aligns way better. But still not good because its adjusted manually

If anyone has an idea, or tips. Its a code i tried to reproduce from a work online but ended up copy pasting it coz of this bug i thought was coming from my version.

true thorn
#

works wonders now ❤️

#

freaking heroes

rich adder
rigid kite
#

I fixed it thanks

rich adder
#

dont crosspost

ivory bobcat
#

!collab

eternal falconBOT
summer stump
lime juniper
#

hello i'm wondering why this entity is not moving at all

 Enemy enemy = collision.GetComponent<Enemy>();
        if (enemy != null) {

            Vector3 parentPosition = gameObject.GetComponentInParent<Transform>().position;
            Vector2 direction = (Vector2) (collision.transform.position -parentPosition).normalized;
            Vector2 knockbackApplied = direction * knockbackForce;


            enemy.Health -= Damage;
            print(knockbackApplied);
            enemy.KnockBack(knockbackApplied);
         }

public void KnockBack(Vector2 Force) {
        rb.AddForce(Force);

        print("AppliedForce");
    }

slender nymph
#

how do you move it normally?

lime juniper
#

i have no clue what u are asking

slender nymph
#

how do you normally move the enemy

lime juniper
#

he doesn't move

#

there no movement as of now

#

i only have knockback

#

and it doesn't work

slender nymph
#

either you've made your rigidbody kinematic or you are doing something else that is affecting its position

slender nymph
#

kinematic rigidbodies are not affected by forces

somber wren
#

like

lime juniper
somber wren
#

it just goes from normal value to 8

#

on the X axis sorry

#

i mean to that offset

#

idk what i'm supposed to get from that debug, i know that this line fucks up my coordonates

#

i'll try things tho ty

summer stump
silent valley
#

Hi. So my player does a little jitter? As seen in the video. I'm aware of why it's happening. The Player moves faster than the camera and my player rotates to the mouse for a split millisecond then centres again. I've got it so while I'm dashing, my player cannot aim, move or shoot. Not sure how to do a work around.

muted wadi
#

I'm a little unsure of what this code does and I wanted to ask here to see if I understand it correctly. As I understand it this code is making it so that the transform's rotation and the camera transform's rotation are are being linked with a delay of .2 seconds.

        {
            transform.rotation = Quaternion.Lerp(transform.rotation,Camera.main.transform.rotation,.2f);```
muted wadi
#

oh

#

what is an interpolation ratio?

rich adder
somber wren
#

its how much it takes from the second value and how much it doesn't take from the first

rich adder
#

say you had .5f
your rotation would be a combination of half the rotation of each

muted wadi
#

oh

#

so if its .2 then is the transform rotating at a rate of .2 as opposed to the camera's .8?

rich adder
#

meaning its at 20% the rotation of your Cam's rotation

#

if you want a smooth transition from one to another you have to increment the value with some timer

muted wadi
#

i still dont understand

#

im sorry

somber wren
#

look up on the internet

#

its maths actually

muted wadi
#

yeah i kinda suck at maths

somber wren
#

maybe there are some videos that makes it simple

summer stump
somber wren
#

i can give you another exemple if you want

muted wadi
#

sure

summer stump
#

If you have values of 0 to 10, and your third parameter is 3, you will just get a 3

muted wadi
summer stump
muted wadi
#

i understand the 0 to 1 part, just not really how it affects the transform and camera rotations

rich adder
#

forget that part. Your lerping between 2 values regardless

somber wren
#

imagine those color tapes, one side if full blue and the other side full red

#

colors in between are obtained by interpolation

summer stump
somber wren
#

like in the middle its 0.5f bc its 0.5 of blue and 0.5 of red

#

yeah

#

transform rotation change each frame

#

so it rotates

rich adder
#

@muted wadi another visual example with rotations (timestamped)
https://youtu.be/1yoFjjJRnLY?t=417
its using SLERP but same concept applies

In this 10 mins GameDev tips we are going to explore Quaternions in an intuitive way. Don't expect deep math derivations. However after watching this video you should have a good mental picture on how they could help you dealing with rotations and orientations in your game projects. I will start by describing euler angles and their issues follow...

▶ Play video
coarse moss
#

question about farming implementation. So I have functionality that you can plow soil, plant a seed and that seed will grow/be harvestable. I currently use SetTile to change the tile from a plow tile to a seed tile. Is there a way to change the image of that specific tile without using the .SetTile method? Is it using some sort of the .SetAnimationFrame method for the tile? then I just have it show a certain animation frame compared to where it is in the growth cycle

muted wadi
#

so its setting the transforms rotation to be 20% cam and 80% original

#

basically the position between those two

rich adder
#

rotation*

muted wadi
#

right

#

what is this useful for?

somber wren
#

to rotate smoothly

rich adder
#

Lerp? like a billion types of use

muted wadi
#

OH

#

it just clicked

rich adder
#

usually smoothing

#

"blending"

muted wadi
#

is that like a transition between one type of thing to another?

summer stump
#

This is a good example of blending

muted wadi
#

oh ok

somber wren
muted wadi
#

i see

#

man, whoever told me that maths wasn't very big of a component in coding lied to my face

#

there is so much math

rich adder
#

even more math in games lol

somber wren
#

IA too nvm

#

and image synthetising too nvm

muted wadi
somber wren
#

go WEB if u dont want maths ig ... x)

muted wadi
rich adder
#

so as long as you know the concept behind something, the code is second

#

esp important Vector math, Trig etc.

muted wadi
#

that's true, but understanding the functions and how they can be applied is still pretty hard

silent valley
rich adder
#

Rotations being the worst imo

final trellis
#

whats an easier or cleaner way to format an integer from 1-3 digits to exclusively be 3 digits ( example, 3 becomes 003, 27 becomes 027 and any 3 digit number is preserved ) without using yucky looking if statements

#

formatted into a string ofc

short hazel
#

num.ToString("D3")

#

Format strings are awesome

summer stump
#

Leave Move() where it is though

silent valley
#

double checked now too. Still the same

summer stump
#

Yeah, I wasn't too hopeful that would do it. BUT you should always capture input in Update. You'll get issues doing it in FixedUpdate

Now, I'm not sure I see what you mean by jitter in that video.

rich adder
final trellis
short hazel
#

Show your code

final trellis
short hazel
#

It's a float isn't it

#

Can't use D with floats

final trellis
#

right ig i gotta add more brackets bc it originally yelled at me for tryna make it an int

summer stump
short hazel
#

Or you can use the 000 format

silent valley
summer stump
#

Ah

rich adder
#

Oh ok now i remember why i used the 000

#

lol

final trellis
#

D3 seems to work fine when I cast to an integer

short hazel
#

Yes, D only works with integral types

final trellis
#

this will vastly simplify a lot of my code bc for some reason im obsessed with formatting numbers that way lol

short hazel
#

The link I posted has a neat table (scroll down) that shows what's supported by which types

final trellis
#

for some reason I also stylize :s into //s

summer stump
final trellis
#

but yeah thanks, v helpful :3

silent valley
summer stump
#

@silent valley Ok yeah I see that more now hmm.

And looking at your code more, you DO disable aiming while dashing 🤦‍♂️. Sorry, should have looked closer.

I'm thinking the mousePosition needs to be guaranteed to update before the rotation, because it's trying to use the LAST position.
So what if you allow ProcessInput even when dashing, and ONLY block Move?

#

Or make a ProcessAim function and allow only that

silent valley
cosmic zenith
#

Hi there people, one question to anyone who might know about this, i have an issue were my character goes trough my tilemap collider 2d and the tutorial i am following says to enable "used by composite" option in the component but i can't find it anywhere, i have 2023.1.13f version, perhaps anyone has sorted this out with this newest version?

summer stump
#

@silent valley The only other thing I can think is to make the rotation smoothed, using lerp or movetowards, but that would affect normal play too.

silent valley
#

Can I just not disable the movement for a few miliseconds longer than the dash duration?

silent valley
summer stump
silent valley
#

Also I appreciate any help. i'm so close to having a mini demo release. just little bits to fix

summer stump
silent valley
#

Would you mind giving me a little hand with that please?

sand kettle
#

Guys, how can I clamp my x rotation?

short hazel
#

Store the rotation in degrees as a variable in the class

#

Add values to that variable. Clamp and apply whenever needed

summer stump
#

I have no idea if it will help or make things worse lol

silent valley
#

I was just on the unity docs reading about quaternion :p

rich adder
silent valley
#

what do you mean by it's a float?

polar acorn
#

that can have decimals

short hazel
#

In Rigidbody2D: public float rotation;

silent valley
#

I know what a float is. I meant I didnt quite understand the reply. If I'm right. does it mean since it only rotates on the Z, it can only ever be 1 number (0,360) plus the decimals?

short hazel
#

Correct

silent valley
#

makes sense

short hazel
#

Since in 2D rotating around X/Y would produce unwanted results (object might be invisible or backwards), they agreed upon using a single float, the rotation around Z

shell ice
#

How would I make a system for it to auto set your height and correctly adjust for arm length. I’m new to this.

short hazel
#
class Sample {
    private float rot;

    void Update() {
      rot = // something
      rot = Mathf.Clamp(rot, min, max);
      transform.rotation = Quaternion.Euler(rot, 0, 0);
    }
}
sand kettle
#

like this?

short hazel
#

Like my code

#

Values you get from transform.rotation are not in degrees and cannot be used as angles

#

Quaternions are complex objects that represent rotation on 4 axes, XYZW

#

Each value ranges from -1 to 1 (float), and represent one rotation component

rich adder
#

^^ On this point, if you're confused when you look at the inspector its big numbers, you're seeing Euler angles

short hazel
#

What you can do though is still use the variable like my code, but accumulate the quaternions, if you need to keep the Y/Z values in degrees.

transform.rotation *= Quaternion.Euler(rot, 0, 0);
//                 ^~ NOTICE MULTIPLICATION ASSIGNMENT

Multiplying two Quaternions adds the second one to the first

silent valley
#

We are all talking about rotations. Does any of this apply to what I'm looking for? 😅

sand kettle
#

what I don't understand is what should I assign the rot variable to? Because for me to rotate my player I'm using Transform.Rotate()

short hazel
#

You can't use transform.Rotate if you want to clamp

#

You need to deal with the clamping, which means you need to assign the rotation after the clamp operation

carmine mist
#

This is def not a coding question, but I can't seem to find the right channel for this ype of question. Unity store's add asset is not working for like literally one asset that is perfect for my needs. Is the a way to reset the store or something similar?

sand kettle
silent valley
short hazel
#

With this, you don't need to use *= anymore for the quaternions

silent valley
# carmine mist Like in files?

in unity you have a windows dropdown. there, you will find "Package manager" . Your asset you added from the store will be there

rich adder
silent valley
#

so the W number is a unique number for every possible rotation?

carmine mist
#

Yeah, I figured out how to get the assets from my assets, the actual issue is being able to add things from unity store to my assets...

short hazel
#

https://en.wikipedia.org/wiki/Quaternion
I decline all responsibilty for any brain damage reading this article may induce

In mathematics, the quaternion number system extends the complex numbers. Quaternions were first described by the Irish mathematician William Rowan Hamilton in 1843 and applied to mechanics in three-dimensional space. Hamilton defined a quaternion as the quotient of two directed lines in a three-dimensional space, or, equivalently, as the quotie...

rich adder
#

oh beat me with da link

short hazel
#

lmao even the image is confusing

silent valley
#

I'm kinda glad I ran into this problem. i feel like I've learnt so much tonight xD

rich adder
#

5D chess brain is needed

silent valley
rich adder
#

but yeah w is just another axis

silent valley
#

fml. All this cause I wanted a cool dash xD

rich adder
#

you're doing 2D you should not be worrying about quaternions

#

just trig lol

carmine mist
silent valley
rich adder
#

why are you disabling rotation during ?

silent valley
rich adder
#

yes gotta think in radians

silent valley
#

just a preference. I could do it without disabling it. but the dash doesnt look smooth

#

i have it so it isnt disabled right now but ideally would like to learn why it does that and how to fix instead of avoiding the hard stuff

silent valley
# rich adder so its solved ?

it is if I don't disable the rotation. (was just a preference because the dashing looks better when rotation locked)

#

Also thank you for teaching me new things. I'll be studying this over the next few days

queen adder
#

is there a max size for custom generated meshes with code

#

for some reason when i try to make mine greater than 200x200 quads it gets weird

ashen ferry
#

65k or so

queen adder
#

is there a way around that?

#

or should i just make multiple meshes

ashen ferry
#

multiple meshes only way afaik but u can google more abt it

queen adder
#

ok thanks

#

it will probably be better to make multiple anyways so i can implement chunks at some point

ashen ferry
#

transform.position = waypoints[waypointIndex].transform.position; this line in Start teleports ur balloon to the start

teal vale
#

anyone know how to check ints without using Update? I'm making a clicker game and once you reach 100 clicks, a win screen appears. Due to the fact that I put my checkers in update, it constantly repeats setting the win screen active instead of doing what it's supposed to be doing. which is restarting the game. I'm not going to restart the scene because I have a private int running in the background to check how many times the player has beat the game. Here's the code: https://paste.ofcode.org/ThYyawh6F3DeadHK7NhhPq

summer stump
#

Then when you win, set won to true

#

It will no longer repeatedly set the win screen active

#

OTHERWISE you can turn score into a property, and in the setter you would invoke an event or call a method when score is 100

teal vale
#

Thank you so much. Forgot bools existed for a moment

#

you're a lifesaver

teal vale
#

Should there be a default state to the bool?

#

it's in the update method

teal vale
#

IT WORKS TYSM!!!

summer stump
teal vale
#

you've got to be the most kind person on this server. every time I ask for help on here, they always do that stupid !ide command

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

teal vale
#

dammit

#

i ided myself

frosty hound
#

Having a configured IDE is required to ask for help here.

teal vale
#

I have

#

i've had it configured for about a year

#

but, now I've got it done

#

so thanks guys

summer stump
ashen ferry
queen adder
north kiln
dim wharf
#

How do I convert the rect transform of a text and a transform of a game object? This is a 2d game and simply assigning a rect transform to something's transform doesn't really line it up

wintry quarry
ashen ferry
#

yea ik u might be turned that off cause ive got default settings kekW

wintry quarry
#

The conversion between a rect transform and world space depends on the canvas render type

dim wharf
#

My canvas type is world space with posx and posy being 0,0 and it has a child with a transform the same as an object in the scene + a child that is text

#

i've been doing trial and error but I can't seem to make those positions equal

polar acorn
#

If you just need text to exist in world space, you should use a world-space TextMeshPro instead of a canvas

ashen ferry
dim wharf
#

oh that's better actually

dim wharf
#

at least its noticeable i guess

ashen ferry
#

kekW yea

queen adder
#

with these noise setting how would i make it look like small hills but then have big mountains in some places, if possible

#

ive been messing with them for a while and cant get it

queen adder
#

how to add something in these options? for when i want to instantly add a prefab i frequently use

void thicket
#

You put menu under GameObject/ iirc

queen adder
#

thanks imma try

echo solar
#

External Dependency Manager is unable to resolve successfully on my new computer, is there anything I have to setup for it to resolve?

echo solar
queen adder
#

Are there a list somewhere of unity methods that can be and can't be called in async?

gaunt ice
#

I think async runs on main thread so any methods can be called in async

teal viper
#

Yeah. And if talking about multithreading, you should assume that none of the API should be used aside from the one that unity specifically uses in jobs system.
Some static utility methods might work on a different thread, but I don't think there's a list of them and you should consider all of the API as not thread safe.

topaz mortar
#

I'm VERY new to Unity and trying to wrap my head around creating an inventory system.
There may be several GameObjects (Player, Store, ...) that have an inventory, so it needs to be re-usable.

How would I set up this Inventory (let's ignore items for now)
Should it be a ScriptableObject? Or just a Prefab? Or?

#

My game is gonna have a LOT of items with lots of attributes, if that is important

charred spoke
#

Well depending on what you want an Inventory can be as simple as List<Item>

#

Now if you want grid based inventory space management things get a bit more complex

strong wren
topaz mortar
#

See this is exactly my problem, I don't know and I don't understand any of that

#

I've followed this really long YT tutorial on how to make an inventory
It had UI controllers, ItemSO, InventorySO, ItemController, ...
It used a Dictionary and a List something something in different locations
And while it ended up working, I do not understand how it works

#

So I just wanna set up something simple right now, that I can later expand to my own needs

strong wren
#

Keep your items in a Inventory Monobehaviour. Have classes like Player and Shop to implement class specific features related to the inventory.

strong wren
inland meteor
#

I'm trying to get movement for 2d, ive got an action of type value with control type vector2 and an up/down/left/right composite thats digitally normalized.
When I try to run it, i can only move horizontally or vertically, not diagonally. i printed the ctx.ReadValue but it only prints [1,0], [-1,0], [0,1], or [0,-1]
how do i get it to output smth like [0.7,0.7]?

gaunt ice
#

some code likes: direction=new vec2(getxasix,getyaxis);
idk if you are using new input system, i dont know how to do it

inland meteor
#

yea im using the new input system

#
queen adder
#

im just starting out coding with unity and i was wondering if dotnet was still supported?

languid spire
queen adder
#

ok thank you im new to this and have been trying for an ungodly amount oof time so i thought i would just check thanks for confirmingUnityChanThumbsUp

teal viper
#

Trying what?🤔

#

Dotnet versions?

queen adder
#

i cant remember the official name but the code support

#

comes up with the list of things u can use

#

ive been using just visual studio

#

so i want to try actually making smth playable

languid spire
eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

worn egret
#

yes, both the extensions are provided by Microsoft - C# and Unity

#

I also use GitLens extension - only the trial version

tawdry bear
#

Hi! May I ask if it's possible to add [animator] component to items in a list?

#

My characters are being spawned from a list to a prefab, I want to give each customer an angry reaction and given them a walk cycle, how should I go about this?

tulip maple
#

Hi. I am having issues with the new VS Code Unity support. When I open VS Code through a script in Unity it always opens a "clean" window with only that one script open. It doesn't remember what scripts I had open last time I used it.
I am pretty sure I have everything setup correctly on the latest versions. When VS Code opens it takes a minute to load the project and the references. Then it works for a little while I can Ctrl+Click classes and methods to see where they get used. When I type I get intellisense with proper methods avaiable etc. But after I change anything in the code and save it, it completely falls apart, Ctrl+Click ends up in loading something indefinitely and I have to close it, let Unity compile scripts and open VS Code again for it to work again. I think same thing happens when Unity is doing something like baking asset bundles or building where the intellisense,etc. stops working.
Is there a way to fix it or find where the problem is?

It would also be nice if the visual studio support package supported forks of VS Code. I was trying to use it with the Cursor editor and only got it to work with some workarounds that break after updating because the package has hardcoded VS and VSCode paths in it.

stiff kettle
#

!code

eternal falconBOT
#
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.

final kestrel
#

https://hatebin.com/icblqngqsr Any idea why my rotator coroutine does not work? I can rotate multiple times on trigger. I want to be able to lock it for .4 seconds.

gaunt ice
#

you even didnt use the canRotate bool....you just set it

final kestrel
#

I added it in the if statement now

#

Yeah my bad. Thanks

languid spire
#

what are you trying to achieve?

final kestrel
#

There are triggers on my scene. When entered my character just turns on the desired axis. If i dont limit the turning, character can rotate 180 degrees or more, which makes it face backwards.

#

I wanted to use a coroutine to limit the rotation event

#

It works fine now.

royal linden
#

can someone help

teal viper
#

Instantiate doesn't take an array as a parameter.

topaz mortar
#

I just started a new 2d project
I have a Character with walk animation, but it doesn't actually move
I also set up a parallax background (auto infinite scroll)
Now when my character gets into combat, I pause the walk animation, but how do I link my background object to this process? So I can also stop the background scroll
I could just add a variable in my character or combat script for the background, but that doesn't really make sense?

royal linden
#

or something

topaz mortar
#

yeah that's not the issue, the problem is I don't know how to link my character & background objects in a proper way

tawdry bear
#

I'm just trying to add this to list to my scene - why can't I add it?

royal linden
topaz mortar
quaint thicket
#

I'm trying to add trees to my terrain but the below code doesn't work. Any ideas?

        public static Terrain terrain; // Reference to the Terrain component
        public static GameObject treePrefab; // The prefab of the tree or vegetation you want to add

        public static void AddTrees(Terrains terr)
        {
            terrain = terr.Terrain; // The terrains terrain
            treePrefab = Resources.Load<GameObject>("Tree9_2");

            TreeInstance treeInstance = new TreeInstance();

            treeInstance.position = new Vector3(Random.value, 0, Random.value);

            treeInstance.prototypeIndex = 0; // Assuming the first tree prototype

            terrain.AddTreeInstance(treeInstance);

            terrain.Flush();
        }```
tawdry bear
#

looks like you're missing a "_"

Where am I missing this?

topaz mortar
#

your class name is AngryCommentList instead of AngryComments_List like in the error

tawdry bear
#

I tried removing the -

#

still doesn't work

#

this script is identical to my other lists - I just copied and paste it in, change the names for another list, so I don't understand why it's not working.

quaint thicket
#

Comments =/= comment

tawdry bear
#

?

quaint thicket
#

The script name is AngryCommentList, not AngryCommentsList. So your script name needs to be AngryCommentList before you can add it.

#

I think

tawdry bear
frosty hound
#

The file name and class name have to match. Do they?

quaint thicket
#

Hmm

tawdry bear
#

My previous scripts didn;t hv the problem despite of the naming conventions being different tho

frosty hound
#

They did, because it wouldn't work otherwise.

burnt vapor
#

File name and class name must match in naming, not in casing

tawdry bear
#

Huh?

frosty hound
#

Just match your class and script names and be done with it.

burnt vapor
#

Because comment is singular in the class name and plural in the file name

tawdry bear
#

This script works perfectly fine

burnt vapor
#

It's not supposed to work and it's a bad habit to do this in general, that's all I can say

frosty hound
#

If you say so. Not going to argue about it.

burnt vapor
#

Unity assumes you have a single MonoBehaviour in a file, and the names match

tawdry bear
#

it's still not working, im not arguing w you

frosty hound
#

All the ones you've sent don't match. 🤷‍♂️

tawdry bear
frosty hound
#

The rest of the error states making sure you have no compiler errors. What does your Unity console show?

tawdry bear
#

Better?

burnt vapor
#

Right, then you have compiler errors

#

Until you fixed the errors, unity is not updating the context it was previously aware of and keeping that error

sand veldt
#

Can anyone tell me like whats the point of creating an interface when i have a complete scripte that control the Health logic

burnt vapor
#

So your enemy must be damageable, you make it implement IDamageable, which contains a contract that tells the class to have health, and a way to apply damage

#

Then when you have your level, and you shoot an enemy, the script checks if the enemy implements IDamageable, after which you can call that damage method

#

And this way you can have it implement many interfaces that define the context of a class

sand veldt
#

but in interface every property is public then anyone can acess the health property isnt bad i mean anyone can change it

burnt vapor
#

You can restrict the get and set parameter if that's an issue. Otherwise don't add it I guess? Although I don't see why you would restrict people from accessing it.

random sand
#
        Quaternion quartRotation =Quaternion.LookRotation(targetRot);
        cj.targetRotation = quartRotation * startRot;```

would this work where cj is a configurable joint?
sand veldt
topaz mortar
#

if your code is working without an interface, why are you trying to add an interface?

burnt vapor
topaz mortar
#

interfaces are pretty hard to understand and only useful in large projects

burnt vapor
#

This way, you can set it inside the class.

tawdry bear
#

Ahh ok that worked, thank you 🙏

burnt vapor
tawdry bear
sand veldt
#

!code

eternal falconBOT
#
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.

modest dust
#

All they do is expand your class and give you the ability to define custom implementation

#

So an IHealth interface can behave differently on two different classes

#

While being able to get in the same way

burnt vapor
modest dust
#

Let's say one class uses defence (enemy) while other doesn't (barrel). You can then implement different DoDamage() methods if it's a part of the IHealth interface

burnt vapor
modest dust
#

Whatever is the case, basically custom behaviour for each class

sand veldt
#

Thanx i got it

random sand
#
        Quaternion quartRotation =Quaternion.LookRotation(targetRot);
        cj.targetRotation = quartRotation * startRot;

would this work? i am trying to set the target rotation of a configurable joint to point to the position of a raycast from a camera

sand veldt
#

https://gdl.space/oleyequgun.cs
just consider this script only contain 3 varibles
int maxHealth;
int health;
[SerializeField] Image healthbar;
i want to convert it to interface
Health class will only contain healthbar and i impliment other stuff on interface will it be faster than health Class or not
i mean i still have to send data to health class to change the health bar

burnt vapor
# sand veldt https://gdl.space/oleyequgun.cs just consider this script only contain 3 varible...

I mean, in my opinion there are multiple things wrong with this.
First of all, I assume various actors in your scene have health. What you should do is define a class for these actors, and have them abstract from a base class that contains this health. You need an abstract class, and not an interface, because there's a base implementation when it comes to health.
Second of all, you should not merge your UI and the actual behaviour in one. You should have a manager, preferably singleton, which manages your UI. This will display the health bar, and not this. If you contain it all in one class it's much harder to manage and will most likely cause bugs.

#

What exactly is going to have health in your game?

sand veldt
#

enemys and player hp

#

and what is less cost effective directly assign a refrence from inspector or throught considring you are creating a large number of enemys

[SerializeField] HealthbarUI hp;

burnt vapor
# sand veldt enemys and player hp

If you want my two cents, make a class Pawn or something that implements this, then have a PlayerPawn and Enemypawn inherit from this. PlayerPawn has all the input implementations, while EnemyPawn has all the NPC behaviour it needs. Pawn implements the shared context, such as health, height, mass, whatever you need

#

You don't need an interface for this

burnt vapor
#

I would advice you make a manager still, but instead of provides this UI to display above the enemy. This way you only assign it once and the enemy can fetch the bar to display on top. Pawn will implement showing this health bar.

sand veldt
#

sorry my internet is not working correctly

#

what is less cost effective directly assign a reffrence from inspector or throught considring you are creating a large number of enemys

[SerializeField] HealthbarUI hp;

or
HealthbarUI hp;

hp=GetComponent<HealthBarUI>();

topaz mortar
#

ok I'm confused:

{
    [SerializeField] private GameObject MonsterPrefab { get; }
}```
```public class CombatController : MonoBehaviour
{
    [SerializeField] private MonsterSO monster;
    private GameObject currentMonster;

    private void SpawnMonster()
    {
        currentMonster = Instantiate(monster.MonsterPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    }

Why does it not find monster.MonsterPrefab?

burnt vapor
#

Either make it public, or keep it private (and make it a field since having it as a property is pointless) and make a seperate get-only property to get the field.

queen adder
#

is it possible to write an attribute for a field that will make it so that when the field was modified in the editor, it launches a specific method?

burnt vapor
#

I made one before but it's stinky

queen adder
#

without the dumb OnValidate

burnt vapor
#

1 sec

queen adder
#

stinky? Interesting

burnt vapor
#

Just bad in terms of performance

queen adder
#

like worst than OnV?

#

tbh OnV is overkill 98% of the time 🥹

burnt vapor
#

No doubt there are better ways to do this

topaz mortar
queen adder
#

havent really wrote an attribute before

#

jg curioused

burnt vapor
burnt vapor
#

Should have mentioned that. That's why they're split

#

Because the attribute is something you implement on fields which is runtime related, and the drawer is the thing invoking editor code when it does its behaviour

#

Just know I made this years ago and I barely worked on that project

#

So idk how reliable it is

queen adder
#

lemi try to add it after my 10 mins debugging sesh

queen adder
#

or not UnityChanOops

teal viper
#

What's the actual question though?

lean basin
#

Hello, what is LayerMask int value for only read object in Layer 0 :Default?

teal viper
#

But to answer you question, it should just be 1, as you need to shift 1 left 0 positions.

quaint thicket
#

I'm trying to add trees to my terrain but the below code doesn't work. It doesn't give any errors but the trees just don't appear. Any ideas?

        public static Terrain terrain;
        public static GameObject treePrefab;

        public static void AddTrees(Terrains terr)
        {
            terrain = terr.Terrain; // The terrains terrain
            treePrefab = Resources.Load<GameObject>("Tree9_2");
            TreeInstance treeInstance = new TreeInstance();
            treeInstance.position = new Vector3(Random.value, 0, Random.value);
            treeInstance.prototypeIndex = 0;
            terrain.AddTreeInstance(treeInstance);

            terrain.Flush();
        }```
stiff stump
#

how can i compare two vector2's to check if they are similar to a certain decimal point?

keen dew
#
(v1 - v2).magnitude < 0.001
#

add as many zeroes as you want

gaunt ice
#

floating point precision is around 10^-6

keen dew
#

right, at some point you can just do ==

unique hull
#

You could also do enumerable.range

stiff stump
#

thanks

slate sun
#

Is there any good lib to extract .zip on IOS? (Async support?) Pls ping

cunning rapids
slate sun
#

It seems has problems exactly with IOS 💀

slate sun
burnt vapor
#

That doesn't matter, you can make it async

#

await Task.Run(() => ZipFile.ExtractToDirectory(...));

slate sun
slate sun
#

90 MB would take some time to extract 😔

slate sun
#

Anyway i'll try, ty

slate sun
burnt vapor
#

Unless I'm mistaken, in which case you just need to call the Task Factory instead

burnt vapor
# slate sun What is not?

This code is not invoked on the main thread since it does not use Unity's synchronization context, as far as I am aware

#

The thing with your question is that you're looking for a system that will still use this synchronization context when it's asynchronous, so you need to do it manually anyway

#

Hence why you should make your own Task

#

If that does not work, you need to go one level lower and instantiate your own thread and run that

#

Either way the main issue is avoiding the use of that synchronization context and a third party library would not fix that

tawdry mirage
#

can getting transform.position and comparing it to other transform.position be noticeably slower than raycast2d? if transform has a lot of parents, getting it's global pos is not that good idea?

cosmic dagger
tawdry mirage
cosmic dagger
tawdry mirage
#

so, 2d devs do that over raycasting? i just wonder if there are some not so obvious downsides

nocturne parcel
#

How do I limit a generic to be a primitive type? I.e, T can only be int, long, double...

cosmic dagger
gaunt ice
#

a similar approach is unmanaged, c# has no keyword of constraint on primitive type afaik

tawdry mirage
cosmic dagger
nocturne parcel
#

ty

void thicket
#

INumber in Unity when

gray talon
#

Hey! anyone here using Neovim on Linux? I got the LSP kinda running but it can't find unity libraries (can't find namepsace when using UnityEngine so the code completion/suggestions dont work.

silent valley
#

When I pause my game. The default cursor shows and my crosshair disappears. When I resume, the crosshair appears and the default cursor stays there until i click my screen, then disappears. Any help?

compact dirge
#

So, i have 3 types of entity class, (Entity and 2 derived class: Enemy and Player).
I have an Attack class too, that have 2 child class: EnemyAttack and PlayerAttack.

Enemy have a public Attack list. How can i have a PlayerAttack list and an EnemyAttack list INSTEAD of the Attack one into the derived class?

#

i can use the virtual and override keys for variable too?

slender nymph
finite star
silent valley
#

I'll try a build and run

silent valley
#

it makes sense

#

pressing ESC enables the editor to be in focus so mouse comes into play. fml

#

it works in build and run

#

Thank you ❤️

topaz mortar
#

What library do I need for Random.Range?
I have using UnityEngine, but it still won't work

swift crag
#

It's not that you're missing a using directive

#

It's that you have too many of them!

cosmic dagger
# topaz mortar

UnityEngine and System both have a Random class. if you have both using directives in your class, you need to specifiy which namespace of Random you're using . . .

swift crag
#

Without using, you must provide the full name of the thing you want. So, for example:

UnityEngine.Random.Range(0f, 10f);
#

using lets you omit that.

cosmic dagger
#

hence the error stating there is an ambiguous reference between the two . . .

swift crag
#
using UnityEngine;

void Whatever() {
  float x = Random.Range(0f, 10f);
}
#

but, as the error states, both UnityEngine and System define Random

#

I generally avoid using System; and just write out the full name of anything I need from that namespace

#

e.g. [System.Serializable]

topaz mortar
#

ah lol thx, yeah I tried adding UnityEgine in front, but it threw another error (I had bad code) 😛 works now ty

swift crag
#

If you want both, you can still fix this:

using UnityEngine;
using System;
using Random = UnityEngine.Random;
#

This will clear up the ambiguity.

nocturne parcel
cosmic dagger
#

yep, an alias will work just fine . . .

nocturne parcel
#

Guess I'm gonna go with IComparable

topaz mortar
#

not even using System, dunno why it's there, removed it

nocturne parcel
#

I thought Unity had support for .net 7?

swift crag
void thicket
nocturne parcel
#

Didn't they add it on 2018?

#

Oooh, it's only .net 6

#

Too bad

void thicket
#

You can use newer C# language featurs with some tweak

swift crag
#

I'm a little fuzzy on all the different .NET flavors

void thicket
#

But not the classes in .NET lib

#

Aka BCL

languid spire
void thicket
#

Tech year 2018

languid spire
nocturne parcel
#

Ah, I see. I got confused then.

cosmic dagger
languid spire
cosmic dagger
#

they're really behind on everything, huh? sad times . . .

languid spire
#

yep a move to .Net 7 is way beyond due and will solve a huge amount of cross-platform problems

swift crag
#

beyond which APIs you can or cannot access

cosmic dagger
#

it's interesting to here that there are multiple versions of .Net available, similar to assets, but isn't complete or up-to-date . . .

stark bronze
#

can you change the type of a navmesh agent in the code?

shy cloud
#

How do you put an UI element (in my case a slider) in front of a GameObject/Sprite?

cosmic dagger
#

ui elements will always display on top of GameObjects (if using screen space ui) . . .

shy cloud
#

My slider is behind all my game objects

#

I'm using Screen Space - Camera

summer stump
shy cloud
#

yes

summer stump
#

Welll.... there you go.
Use a sorting layer to put it behind. Or have it not as a child

shy cloud
#

If I remove the game objects and the slider from the canvas, they disappear

cosmic dagger
#

the slider must be part of the canvas . . .

summer stump
#

Why remove the slider? And what is the z position of the objects and the camera?

shy cloud
#

But the slider should be a child of a game object bc it should only be visible when a certain menu is active and this menu is a game object, but it should obviously display in front of the menu

#

Also, the script which toggels the menu is in the canvas

summer stump
#

Then use a sorting layer like I suggested 🤷‍♂️
Or a worldspace canvas for the slider

shy cloud
#

But how can I add a sorting layer to a UI element?

wintry quarry
cosmic dagger
#

you can use two cameras. one for ui using depth only and set that camera for the canvas. make sure the main game camera culling mask does not have the UI layer . . .

shy cloud
shy cloud
#

ty

shy cloud
nimble kernel
#

Hello everyone !
I have a problem with the scenes in my game.
I have a "MainMenu" scene, and scenes for my game levels.
Starting the game, the main menu behaves normally, lets the player go to the level they selected (which is a new scene). when they get back to the main menu, some things do not work correctly.
I think it's because it's basically returning to the same MainMenu scene it first created, going through its Start function again, even though some things were left over ?
Is there a way to tell Unity to clear totally the scene instead of taking the one it created before ?
One of the things that do not work correctly when going back to the MainMenu, is the functions affected to the PlayerInputs in the Start of the MainMenu.
I tried to use a boolean to only add them to the first call of Start, but even that is not great : it looks like they're reading old values of some booleans, and not doing things correctly.
Do you guys have any advice on ho to handle that ?

copper perch
#
using UnityEngine;

public class ZombieBossParticleActivateWhenAnimationPlays : MonoBehaviour
{
    // Reference to the Particle Systems on the zombie boss's fists
    public ParticleSystem[] fistParticles;

    private Animator animator;
    private bool particlesActive;

    private void Start()
    {
        // Get the Animator component of the zombie boss
        animator = GetComponent<Animator>();
        particlesActive = false;
    }

    private void Update()
    {
        // Check if the specified animations are playing
        bool isPlayingSpecifiedAnimation =
            animator.GetCurrentAnimatorStateInfo(0).IsName("Combination boxing zombie quad punch") ||
            animator.GetCurrentAnimatorStateInfo(0).IsName("Combination boxing zombie punching bag 2");

        // Toggle the Particle Systems based on animation state
        if (isPlayingSpecifiedAnimation && !particlesActive)
        {
            // Start the Particle Systems
            foreach (ParticleSystem particleSystem in fistParticles)
            {
                particleSystem.Play();
            }
            particlesActive = true;
        }
        else if (!isPlayingSpecifiedAnimation && particlesActive)
        {
            // Stop the Particle Systems
            foreach (ParticleSystem particleSystem in fistParticles)
            {
                particleSystem.Stop();
            }
            particlesActive = false;
        }
    }
}```
polar acorn
#

If that's not what you're getting, then you've got something that's persisting between scenes like a DDOL or some sort of serialized data

copper perch
#

I am trying to get my combo boxing zombie boss to make 2 particle systems that make his fists glow when he does a combo punch animation.
Both the particle systems would switch off after he does the punching combo animation.
The particle systems on the zombie boss model, as a child of his fists.
The animation is from mixamo.
I turned the particle systems of when they are a child of the fists, and I adjusted the particles correctly on the fists.
Chat GPT wrote me this script but its not working for the particles systems to switch on when the combi boxing zombie boss does the 2 animations:
Combination boxing zombie quad punch
Combination boxing zombie punching bag 2
Can you help me get it going?

polar acorn
shy cloud
#

Why doesnt Unity allow me to create a slider object?
slideFPS.cs(8,12): error CS0246: The type or namespace name 'Slider' could not be found (are you missing a using directive or an assembly reference?)

topaz mortar
summer stump
eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

summer stump
summer stump
#

You have UnityEDITOR.UI

#

You need UnityEngine.UI

shy cloud
#

oh

summer stump
graceful flicker
#

Should items be created using scriptable object or oop?

polar acorn
#

Not mutually exclusive concepts

graceful flicker
#

Does this even makes sense?

polar acorn
#

Item could be an SO instead of a Monobehaviour

graceful flicker
#

So when I want to do it this way, when I create a list it will be a type of "Item" and it will store all item types? So will there be one list storing tooli tems, healing items, block items...?

graceful flicker
#

So when I create items they don't show up in inspector. Why is that happening?

eternal falconBOT
#
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.

graceful flicker
rich adder
polar acorn
graceful flicker
polar acorn
shy cloud
polar acorn
#

which cannot be created with new

graceful flicker
summer stump
graceful flicker
#

So basically I have to create a SO class which will store all settings and then create new SO item and set it's value to that Item class settings?

rich adder
summer stump
#

I agree with Nav, I don't like to have mutable SOs

rich adder
#

learned the hard way 😛

#

I suppose for InEditor settings its okay

graceful flicker
summer stump
shy cloud
#

Ty

cosmic dagger
rich adder
carmine mist
#

Is there an efficient way to generate a random number with discontinuities/unity

#

I've thought of two solutions using a another random number to change the range (1 correspond to x1 to x2 2 to x3 to x4)

#

Or just using if statements, but is there a less intensive way?

carmine mist
#

Rand(x1, x2 or x3, x4)

#

Basically I want number between 1 - 10 or 20 - 30

rich adder
#

could always store them in arrays and randomize that

cosmic dagger
carmine mist
#

Okay that's what I was gonna do

#

But just wanted to check if there was a more built in function

rich adder
carmine mist
#

Exactly it thanks

lavish grotto
#

I am using a Profile SO to save data between scenes. After typing a name the player presses a button to accept (the bit in the else statement).

public void AcceptProfileName()
{
    string lProfileNameString = fInputFieldText.text;
    if (DoesProfileExist(lProfileNameString) || lProfileNameString.Length == 1)
    {
        Debug.Log("You didn't enter a name or that name already exists!");
    }
    else
    {       
        _playerProfile.CreateNewProfile(lProfileNameString);
        //display new profile on screen
        _activeProfileManager.SetActiveProfile();
        // Load to game selection scene
        SceneManager.LoadScene(_GAMESELECTIONSCENE);
    }
}

Part of the SO.

 
public void CreateNewProfile(string aName)
{
    _name = aName;
    _coins = "0";
    _collectionScrollList = new List<string>();
    _itemNameList = new List<string>();        
    _itemPositionList = new List<Vector2>();
    SaveSystem.SaveProfile(this);
}```

This works as expected. I can play the game get coins on populate the JSON as expected.
```json
{
  "_name": "Profile1​",
  "_coins": "16",
  "_collectionScrollList": [],
  "_itemNameList": [],
  "_itemPositionList": [],
  "name": "Player Profile SO",
  "hideFlags": 0
}

The problem comes in when I try to load a selected profile instead of creating a new one. I load the profile, display it on the screen, then immeadiately load into the next scene.

else
{            
    Debug.Log("Before: " + _playerProfile._name);
    
    _playerProfile = SaveSystem.LoadPlayer(_thisText.text);
    
    Debug.Log("After: " + _playerProfile._name);
    //Load Game Selection
    SceneManager.LoadScene(_GAMESELECTIONSCENE);
} 

The first debug line will return the name of the previous profile that I loaded, the next one will return the one I am currently trying to load. The correct profile will briefly show then the one that I previously load will show.

#

Once in the next scene the profile I just loaded (shown above) will not be shown nor in the SO. Is there a reason the SO wouldn't hold the data? (Here is my load method)

public static PlayerProfile LoadPlayer(string aProfileName)
{
    string lPath = Application.persistentDataPath + ProfilePath(aProfileName);
    PlayerProfile lProfile = ScriptableObject.CreateInstance<PlayerProfile>();

    if (File.Exists(lPath))
    {
        string lJson = File.ReadAllText(lPath);
        lProfile = JsonConvert.DeserializeObject<PlayerProfile>(lJson);
    }
    else
    {
        Debug.Log("File not found! " + lPath);           
    }
    return lProfile;
}
ivory bobcat
lavish grotto
#

I have no problems changing what I use to transfer data between scenes, what would you recommend?

I was using Dontdestroyonload but I had issues when going back to previous scenes and read that you shouldn't use it for things like that. (idk I am still learning)

ivory bobcat
#

Either save data to and from disk or DDOL Singleton etc

lavish grotto
#

Saving/ loading to disk between scenes doesn't cause too much overhead? I know my game is small and it won't matter but just thinking of being efficient.

ivory bobcat
#

Or a static class that reads data initially from disc etc

amber nimbus
#

Hello, I have this code for simulated suspension. However the wheelObject always moves down by -springLength and if the tank flips then the wheels clip through. I need to somehow get the direction in which they should move on the Y axis
wheelObject.transform.position = Vector3.MoveTowards(wheelObject.transform.position, new Vector3(transform.position.x, transform.position.y - springLength, transform.position.z), 0.3f);

ivory bobcat
lavish grotto
#

Hmm, ok. I think I will look at droping the SO for a static class to see if that fixes my problem.

#

Thanks!

zenith cypress
#

I/O operations are probably some of the most slow tasks you can do LUL Definitely don't want to be doing that like every frame and what not

wintry quarry
#

It shouldn't be done on the main thread in any case

lavish grotto
#

Definitely wouldn't be doing it that often. It is a game of small math problems so it would only be done at the conclusion of each math problem/ scene transition.

ashen ferry
#

Save profiles as jsons then pull them all in profile choose menu discard everything what wasnt chosen and set profile u gonna use in somewhere only one read

lavish grotto
#

Yep, that is exactly what I am doing. I was storing the current profile(the one selected) in a SO for scene transitions but for w.e reason the SO isn't getting updated after a scene transition.

ashen ferry
#

yea weird I was on project like month ago turret defense game turrets are upgradeable and those upgrades persist permanently was stored in SO lots of modifying them but each one had its own asset to edit and didnt use ScriptableObject.CreateInstance whatever that does kekW didnt have a single issue

lavish grotto
#

It is weird, as soon as I get to a new scene after loading the profile the SO has data for something else. Not what I had in just the previous scene. 😦

short hazel
#

A word of warning, scriptable object behave differently in standalone builds. Data you put in them will not be persisted across game restarts

#

Unlike in the Editor

#

Hence why it's strongly advised to not change it (mutate it) at runtime

lavish grotto
#

Thanks for that. I wasn't using them for game restart persistance, just for scene persistance.

#

Ill keep it in mind for the future.

short hazel
#

Surprise! Your save system you spent 3 hours making doesn't work in builds

upper gyro
fervent steppe
#

!bug

eternal falconBOT
#

🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!

💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

shy cloud
#

Dont know why I cast it as well

swift crag
#

rule of thumb: the type of a member can't change

#

not unless the object has a <generic type>

#

List<int> holds int and List<float> holds float

shy cloud
#

makes sense ig

swift crag
#

because that almost certainly loses precision

#

it does have an explicit conversion

#

which is why you can cast with (int)

fervent steppe
wintry quarry
ashen ferry
#

did u try going into task manager maybe u can find it open there lol

fervent steppe
#

done both

wintry quarry
# fervent steppe done both
fervent steppe
#

cant open temp

#

corrupted

wintry quarry
#

delete it

fervent steppe
#

cant

#

its corrupted

unreal imp
#

guys, how do I access a child gameobject of an alternate gameobject that I have in the script? (when I say alternate I mean that it is not the one to which the script is applied and you can access it with just gameobject and that's it) I want to access a script of the child object

ivory bobcat
#

You could try Get Component in child

swift crag
#

GetComponent<Foo>() is the same as writing this.GetComponent<Foo>(), and for components, calling someComponent.GetComponent<Foo>() is the same as doing someComponent.gameObject.GetComponent<Foo>()

#

so, if you have a field called theObject that stores a GameObject, you can do everything with that object that you can do with the one stored in gameObject.

ashen ferry
#

how could I gobble something really fast to leave like txt file of what happened before the lights go out my game crashes in pc build bruv

ivory bobcat
#

Reminder that

Whether or not finalizers are run as part of application termination is specific to each implementation of .NET.

swift crag
#

a native crash will not really leave time for anything to happen at all

azure kelp
#

I want to get started with shaders. I will use them to render some simple shapes for now, like a circle, based on an object. How should I go about it?

ashen ferry
swift crag
azure kelp
modern smelt
#

Hello guyz , i have some problem with my code , i'm sure that this is a stupid error of newbie xD
I want to outline a block when i'm looking at. And turn off the outline when i'm not looking at anymore.
I made a script where the outline work at the first time i'm looking at the object , but dont turn it off when i'm looking somewhere else.
The script is turned off when i launch the game , turn off when i 'm looking object and suppose to turn off when i'm looking somewhere else
Please help me xD

rich adder
swift crag
#

If you look from one outline-able object to another, you will not turn off the first outline

#

Two steps: decide if you're no longer looking at the old object, then decide if the new object can be outlined

rich adder
#

thats a big conflict

modern smelt
rich adder
#

gameObject already is the gameobject the script is on

rich adder
modern smelt
rich adder
#

rather store the Component , eg Outline

swift crag
#

yes, store the Outline itself

swift crag
#
  • If you are looking at an outline-able object, outline it
  • Otherwise, if you are not looking at an outline-able object, stop outlining the object you were previously looking at
#

Instead:

#
  • If you are not looking at an outline-able object, stop outlining the object you were previously looking at
  • If you are looking at an outline-able object, and it's not the same as the previous object you were looking at, turn off the outline on the previous object
  • If you are looking at an outline-able object, outline it
#

i guess you could simplify that to

#
  • If the object you're looking at is not the same as the previous object you were looking at, turn off the outline on the previous object
  • If you are looking at an outline-able object, outline it
modern smelt
#

how can i store outline ? i can make a private var get component ?

swift crag
#

store it like you store literally anything else

#

make a variable of the appropriate type and store a value in it

#

so, declare Outline previousOutline; in the class, then do previousOutline = hit.transform.gameObject.GetComponent<Outline>(); to store something in it

modern smelt
#

and how would it make work better ?

#

because its actually doing the same things but juste a var stored no ?

polar acorn
#

You have no reference to it once it stops being looked at

#

So you store the outline you've looked at before and compare it to what you're currently looking at, and if it's a different thing, you use the reference to the old outline to disable it

modern smelt
#

you mean like this ?

polar acorn
# modern smelt

Just store it in a variable of Outline type instead of a game object

swift crag
# modern smelt

previousOutline is not very useful if you instantly overwrite it

#

Check if the object you are currently looking at has an Outline

#

if that's a different outline than previousOutline, turn off the old outline

balmy briar
#

anyone know how to attach "animator.SetBool("isjumping", false);" to my ground check so it stops the jump animation once i hit the floor instead of looping? (im really new to scripting)

swift crag
#

just...call the method?

#

if your ground check says you're on the ground, then run animator.SetBool("isJumping", false);

azure kelp
tiny leaf
#

What kind of approach could I go for having an enemy spaceship always fly towards player in 3D space, but avoiding collisions with planets?

swift crag
#

Shaders can certainly be used to draw shapes -- you put it on a quad (a square mesh)

summer stump
swift crag
#

that's a good way to do pretty UI elements

modern smelt
swift crag
#

if the outline is not null, the object has an outline

#

or, even better

tiny leaf
#

is there some kind of basic pathfinding I could try to implement instead of trying to make 3 dimensional A*?

swift crag
#
if (someObject.TryGetComponent(out Outline outline)) {
  // do stuff with the object's outline
}
#

this creates a new local variable called outline

swift crag
#

then, I'd raycast forwards and, if a planet is hit, steer away from the planet's center

#

If the planet density is low, this will work well.

summer stump
#

But yeah, what fen is saying would be simpler for sure

swift crag
#

well, it'd be A* with a graph representing 3D space, and creating that graph is non-trivial

#

even more non-trivial than usual!

cosmic dagger
tiny leaf
#

Okay thanks guys

summer stump
swift crag
#

This sounds a lot like "boids" to me.

#

at least, the first part of boids: separation

azure kelp
swift crag
#

anything that's too close to you makes you want to move away

swift crag
azure kelp
#

Uh well, I don't even know what shader graph is tbh

swift crag
swift crag
azure kelp
#

Oh I didn't know there are ui elements like this, this is very helpful

swift crag
#

Try attaching various nodes to the output to see what the values look like

azure kelp
#

I'll give it a look, thanks

swift crag
#

i'd start with an unlit shader graph

#

red is X, green is Y

#

I struggle with this because I'm partially red-green colorblind 🫠

#

but anyway -- feel free to ask in #archived-shaders if you have more questions. that's the best spot for this

azure kelp
#

Hmm interesting

#

What does this square represent?

swift crag
#

It's just a Plane (GameObject -> 3D -> Plane)

#

its UV coordinates range from [0,0] in one corner to [1,1] in the other

#

this shader just directly outputs the UV coordinate of each pixel as the color of that pixel

azure kelp
#

So basically, there's a plane, with some material, the material has this shader and the shader is calculating the pixels on what I assume is a texure?

swift crag
#

There is no texture involved here.

#

A texture is an image that you can sample colors from.

#

This shader does not use one. It just turns the UV coordinates directly into colors.

#

neither does this one, which is literally always red

azure kelp
#

So this renders on the plane directly?

swift crag
#

Well, it's unlit, so it doesn't care about lighting at all. But I wouldn't say it's any more or less "direct" than any other shader

azure kelp
#

Hmm, I suppose a comprehensive introduction to shaders would be most beneficial to me, thank you for your time!

twin bolt
#

I have a laser wall in my game that rises using a animation, but i also want it to be reversed the next time the animation is enabled, can i change the animation speed during runtime?
without using multiplier

swift crag
#

"multiplier"?

twin bolt
#

speed multiplier

#

but i figured it out

radiant moon
#

Hey

#

Someone that can help me out could text me on the DM?
I have a lot to send and i need help with my code

swift crag
#

Ask your question here.

radiant moon
#

Ok then

summer stump
#

@radiant moon for code use the instructions here

eternal falconBOT
#
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.

radiant moon
#

ok

#

Can i send like, one line of code here?

summer stump
#

Sure of course. It shows how to do that in the instructions near the bottom

#
My code here 
radiant moon
#

oh ok

slender nymph
#

backticks not apostrophes

radiant moon
#
 CreateObstaclePair(startPositionX, Random.Range(minH, maxH), obstacleGap);
radiant moon
slender nymph
#

you'll need to show more code than that

tame thorn
#

I have a sword as a child of the player. I want the sword to move in relation to the player, but its just going to a specific x and y in the map.

public class SwordController : MonoBehaviour
{
    public Transform swordCursor;
    public Vector3 defaultPosition;
    public Quaternion defaultRotation;
    public float rotationSpeed = 5.0f;

    void Start()
    {
        defaultPosition = transform.position;
        defaultRotation = transform.rotation;
    }

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (swordCursor != null)
            {
                //Point towards SwordCursor Object
                Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
            }
        }
        else
        {
            // Smoothly move back to default position and rotation
            transform.position = Vector3.Lerp(transform.position, defaultPosition, rotationSpeed * Time.deltaTime);
            transform.rotation = Quaternion.Slerp(transform.rotation, defaultRotation, rotationSpeed * Time.deltaTime);
        }
    }
}
radiant moon
#

the only thing not working is the randomization of the obstacles size

slender nymph
#

if you look in the inspector for the GameLevel object, what is the value of the minHPossible variable?

radiant moon
#

10

#

actually

#

oh no

#

its 10

#

i thought i was seeing it wrong

somber wren
radiant moon
#

me too

unkempt locust
#

I NEED HELP

unkempt locust
#

How can I learn more about the unit, I watch the tutorial and I feel like I just memorize the code and do it, and that's really boring man, I want to learn it myself

eternal falconBOT
#

🧑‍🏫 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/

pseudo frigate
#

i have a side scrolling platformer where i want the player to be able to create blocks, would physics.boxcast be a good way to ensure the space is available before creating the block, or is there a better way i could go about doing it?

unkempt locust
#

I want to learn camera by myself

polar acorn
#

A boxcast is like firing a cardboard box out of a cannon and seeing what it hits

frosty hound
unkempt locust
polar acorn
#

An overlap box is checking if things exist inside of a cube in world space

pseudo frigate
#

good to know, thank you!

unkempt locust
#

I can't do it man, Some things I always need to see a tutorial and the things I can do, and because I memorized some codes

polar acorn
# unkempt locust omg

Not sure what else you expected. "I want to learn but not use tutorials" -> "Then figure it out yourself" -> Surprised pikachu face

unkempt locust
#

please help me

polar acorn
#

and so did Osteel

frosty hound
#

You're being silly. If you want to learn, use a tutorial and practice what it shows you. If you don't want any tutorials, then tinker around and figure it out yourself (you likely won't be able to).

#

Otherwise, read the Unity Docs if you're so inclined.

pseudo frigate
#

@unkempt locust i would recommend just following a tutorial of a game genre that interests you, youd be surprised how quickly the training wheels come off and you start doing things on your own without needing to copy the tutorial. i went through one brackeys series (tower defense) and things started to click for me

summer stump
ashen ferry
#

aint no way so many ppl got baited on kekW

polar acorn
polar acorn
radiant moon
radiant moon
polar acorn
#

Investigate if those values are what you expect them to be

calm coral
#

You may better remove that sus link from your profile @unkempt locust

radiant moon
radiant moon
#

how do i make it random

polar acorn
#

minH and maxH are both 100

#

Now, try logging those and see what they are, and log the values that make them up

#

Find out where the math isn't mathing

#

A value is different than you expected it to be

radiant moon
#

Ok

somber wren
#

yeah just like me

#

and i cannot find why since 2 days x)

ashen ferry
#

https://hatebin.com/zmiteecdas what is this param: actual param thing called I want to turn it off ide prioritizes that over actual variable if name is same between methods but idek what that is what I google for

calm coral
ashen ferry
#

I pass in method parameter with some sort of prefix

#

wtf is that prefix

queen adder
#

does Transform have a sortchild method?

#

setindex feels weird to be the only option to sort heirarchy via code

ashen ferry
#

no u just set appropriate indexes in a loop and its sortchilds method with extra step kekW

queen adder
#

this what me is doing now 😭

#

                    item.transform.SetSiblingIndex(craftableCount);
                    RecipeHolder elementToMove = RecipeHolders[i];
                    RecipeHolders.RemoveAt(i);
                    RecipeHolders.Insert(craftableCount, elementToMove);
#

looping a duplicate list

ashen ferry
#

AAA so u can pass in variables in any order with this huh cool

tacit estuary
#

hopefully it still help, I only just realized how long ago you asked 😅

stiff stump
#

looking for advice on how a reccomended way of having a health bar under every mob would be
without having too many canvases etc

calm coral
#
public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)
```Like this one
queen adder
#

look in your canvas, and change it to world space

#

also not a code q btw, but pretty sure that's should be enough to send you off

stiff stump
queen adder
#

yea just keep using that canvas

tacit estuary
summer stump
calm coral
calm coral
tacit estuary
calm coral
tacit estuary
tacit estuary
#

Attributes use square brackets []

calm coral
ashen ferry
#

is there any difference between string optionalstr = "a" and [Optional] string optionalstr as param actually theres some regarding default value I cant set it to [Optional] case lol

calm coral
ivory bobcat
pliant bridge
#

hi, im somewhat new to unity, and I noticed that when I use OnTriggerEnter or OnCollisionEnter or any of its variants, it doesnt only checks the collision with the collider attatched to the object holding the script, but also any collider in its children GOs, is that supposed to happen?
if so is there a way for me to specify which collider to check on those methods?
or am I supposed to make multiple scripts and GOs and have each holding their own collider and script and make them exchange info with the main object?

teal viper
pliant bridge
#

oh so if none of them have a rigidbody then then the parent wont check the collision of colliders attached to its children is that right?

compact dirge
#

So, i have a list of Attack, a class that i've created.
Attack need to get access to an entity, another class.
When in my Entity i add the attacks on the list form the inspector, how can i give the reference of this entity to the attacks / how can i let the attacks thake the reference of the Entity where the list is?

teal viper
teal viper
compact dirge
teal viper
compact dirge
#

The attack damage is a property that needs the list of buff every get

teal viper
#

Maybe instead of making it a property, calculate it during the attack. The attack would probably be initiated from the entity, so you can pass all the required info there.

compact dirge
#

so no way to get the Entity from the Attack? WOuld be good to just put in the costructor on the attack, if possible

compact dirge
teal viper
#

There are ways, as I mentioned in the edited message, it would just sort of lead to a spaghetti code if you ask me.

compact dirge
#

maybe i can just pass it during the start at the whole list yeah...

teal viper
#

Typically, you'd have one way reference hierarchy. Both way reference is not a great practice.

compact dirge
#

it's a simle solution and should work

teal viper
compact dirge
#

yeah it's monobehaviour

#

can i have property into not MonoBehaviour too?

sour fulcrum
ashen ferry
#

unity devs with the code smell 😠

teal viper
ashen ferry
#

if u post ur exact setup it would be easier to spot what u can do with that list of attacks btw

summer stump
teal viper
sour fulcrum
#

Forsure Forsure 🤝

compact dirge
#

i don't like this

summer stump
#

@calm coral rude. I wanted to see what happened at 100%

calm coral
queen adder
#

how would i make it so that if a wall comes in between my character and the camera it becomes slightly transparent

summer stump
#

Someone linked a thing from URP that could do it recently, lemme see if I can find it

unique violet
#

I'm trying to destroy an object using Destroy(); but how can I get around this error?
Can't remove RectTransform because Image (Script), Image (Script) depends on it

wintry quarry
#

It's not possible to have a GameObject without a Transform

unique violet
#

but i want to destroy the gameobject

unique violet
summer stump
unique violet
#

woops i just noticed i passed in a parents child which is the transform

queen adder
unique violet
#

thanks though

ashen ferry
#

I was dealing with nasty crash in build tried logging everything what comes in from Application.logMessageReceived but nothing, somehow by chance I got editor to crash in same way and editor logs did have my error in there how come? How can I access that deeper level of logging bruh idk what would I do if editor logs wouldnt saved me 3hrs into this sadok particular error was file lock from what I understand so kinda makes sense if its out of that event territory ig but damn thats a weak ass logging if u ask me

summer stump
teal viper
#

There should be some crash logs in the build as well. They might not be as verbose, but there's no way, it just ends without any mention of the crash.@ashen ferry

#

And a development build should have around the same level of verbosity as the editor I think.

ashen ferry
#

yea so I migjht be retarted

#

where do u find pc build logs or did u mean my logging should of been close enough to editor logs

swift crag
ashen ferry
#

it was sarcasm bro

swift crag
ashen ferry
hollow kraken
#

I have wave based game and I want to make a timer that displays and continuously updates. How would I do that...I tried OnGUI but it would not update jus remained static

swift crag
#

OnGUI only draws to the screen for one frame

#

so it's very unlikely that it's not changing!

#

perhaps your timer isn't counting up

ashen ferry
#

can I do anything about this here I tried lambda trick ive found but it still doesnt compile tho can always pepper around #if ig

hollow kraken
#
public void OnGUI()
    {
        // Increase the time in minute:second format
        int mins = Mathf.FloorToInt(elapsedTime / 60);
        int secs = Mathf.FloorToInt(elapsedTime % 60);

        // Display the time on the bottom right of the screen
        string time = string.Format("Time Survived: {0:00}:{1:00}", mins, secs);
        GUI.Label(new Rect(Screen.width - 100, Screen.height - 100, 100, 50), time);
    }
#

this is what i currently have

swift crag
#

Show your whole script

#

!code

eternal falconBOT
#
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.

calm coral
ashen ferry
#

im giga sleepy but looks like it still leaves in the method just takes care of the calls? But method param uses enum which I cant have in builds either tbh that attribute lowkey useless

calm coral
ashen ferry
#

yea thats what I do usually but I saw conditional attribute few days ago

#

tried to flex around it

#

yea yea sure

teal viper
unique violet
#

How can I make a script that lerps to a specific index in a horizontal layout group. I want to lerp the layout group object to put a specific child object in view. Im currently just figuring out raw positions. Is there any other ways?

royal linden
#

whys it only going up and across

gaunt ice
#

You set the y component of vector3

#

Your animator uses z component so i think you want to set the z of the movement vector

polar acorn
polar acorn
royal linden
unique violet
polar acorn
royal linden
#

brb

polar acorn
polar acorn
solar tide
#

I'm making a card game and progress is going fine but I'm completely stumped on how I'm supposed to program chain links? Basically chain links are something that goes, turn player activates an effect(chain link 1) then the opponent is given a chance to respon with an effect and if they do that effect is chain link 2 then you are able to respond with a card effect. So after both players say no to further activation, the chain resolves, resolving every effect that was activated in chain.

I've pretty much got my cards moving and summon able and they can attack and use effects but I just didn't implement chain links at all cause as I have figured, they seem hard to do. Any tips? How should I go about doing this?

polar acorn
royal linden
#

yes.

polar acorn
#

So what comes after X

royal linden
#

y

#

oh wait

polar acorn
#

So if you have a vector where the first thing is set to horizontal, that's x

#

And if you set the one after X to vertical

#

Which one did you set to vertical

royal linden
#

up

polar acorn
royal linden
polar acorn
# royal linden y

Correct. So, you have a vector where the horizontal axis is x. The vertical axis is y, and 0 is z

#

So when you move your object by that amount

#

Which letters are changing

royal linden
timber tide
#

Ideally you've a statemachine set up

royal linden
polar acorn
solar tide
timber tide
#

Coroutines for the animations, but not the actual logic, right?

solar tide
solar tide
#

I do not have statemachine

timber tide
#

Yeah, it's fine. Something to look into if you go start up another similar project, but polling the state each update is fine. Do change your statements to include 'else if' however so your code can fallthrough without checking each 'if' condition.

royal linden
gaunt ice
#

You get axis on the same axis

royal linden
#

dont mind the end i changed it after ss

gaunt ice
#

And you should normalize the movement vector (you can use getaxis raw here), since the speed(magnitude) of “diagonal” movement is faster if you press a/d and w/s same time

royal linden
#

yea

timber tide
#

And perhaps some situations that would require to be resolved

solar tide
gaunt ice
#

new vec3().normalize (or movement=movement.normalize after you initialize the movement vector)

royal linden
timber tide
# solar tide When a unit(the creatures or monsters of this game) attacks or moves, they decla...

"When a unit(the creatures or monsters of this game) attacks or moves, they declare attack/movement an after the declaration the turn player is prompted to activate a card if that card is activatable. "

This would just be another condition to check and then prompt the user if it's possible. If accepted, then it will have to wait until input for the opposing player to make a move or decline. It would just be in a state of resolving, ping-ponging between player inputs, and until it resolves you just keep going back into this state.

#

It's a subsection of logic that would probably apply in different phases, so probably some additional methods.

subtle folio
#

Hi, im working on a ecosystem simulation game. Im wondering which is better for the creatures, using prefabs or using scriptable objects for each species?