#archived-code-general

1 messages ยท Page 312 of 1

solar wigeon
#

i do that by changing the interactable to on and off

leaden ice
#

oh that's simple

#
void UpdateUI() {
  for (int i = 0; i < maxDashCount; i++) {
    DashUiElements[i].SetActive(dashes >= i);
  }
}``` Something like this. Just call it whenever `dashes` changes.
#

it assumes you put the images in an array or list called DashUiElements

#

which you should

solar wigeon
#

DashUiElementsthis would a object ?

leaden ice
#

it would be an array, as I just mentioned

solar wigeon
#

public Array DashUiElements; like this ?

rigid island
solar wigeon
#

arrays are op i was trying to do the samething i completlety forgot about arrays THANK YOU

#

how do i set a ui toggle to array to a string i trieed public toggle[] whateverthetogglenameis

solar wigeon
#

"how to define here ?"[] DashUiElements = (DashChance1, DashChance2);

naive swallow
rigid island
solar wigeon
#

yea i found it

mental ether
#

hi, i have a character jumping in the editor but not when i build and im not sure if its to do with my code or not but i suspect it is

#

` private void Update()
{

    if (horizontalInput > 0.01f)
        transform.localScale = new Vector2(-0.5f, 0.5f);
    else if (horizontalInput < -0.01f)
        transform.localScale = new Vector2(0.5f, 0.5f);
    anim.SetBool("run", horizontalInput != 0);

    if (CrossPlatformInputManager.GetButtonDown("Jump") && isGrounded)
        Jump();

    if (Input.GetKey(KeyCode.Space) && isGrounded)
        Jump();

}

void Jump()
{
    body.velocity = new Vector2(body.velocity.x, speed);
    isGrounded = false;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Ground")
        isGrounded = true;
} `
#

my jump code

solar wigeon
#

why is this happening the cooldown works once then it just gives me infinite dashes
and i want my button to change the interactable function not visibility

#

!code

tawny elkBOT
solar wigeon
#

send ur code from here

rigid island
#

use link

rotund ember
#

all sorted sorry about that

solar wigeon
rigid island
solar wigeon
#

make dashchange to toggle[] instead of gameobject[]

leaden ice
#

Basic C# syntax errors.

solar wigeon
#

what should i do?

leaden ice
#

Use the correct property or function

#

This isn't what you want

solar wigeon
#

but my ui button works from interactable i dont want it to be setactive

#

and some of you code have problems after 2 times dash i get infinte dash with no cooldown

leaden ice
#

This isn't how you set whether a selectable is interactable

#

Didn't you have code doing it before? Why are you suddenly trying to use a different function

solar wigeon
leaden ice
#

You forgot something

mental ether
#

here is video of editor and then of build, in both i press space and for some reason it wont work in either my ios build or my windows build but it works perfectly fine in the editor, cant find anything online as to why this is happening

leaden ice
mental ether
solar wigeon
#

now ?

leaden ice
#

You tell me, is it working?

mental ether
solar wigeon
ashen kettle
#

Hi all, I was wondering if anyone's familiar with Unity's ML Agents. I am trying to use ML Agents to play flappy bird, but my code doesn't seem to function correctly. I can't get the neural network to learn. If anyone can help, that would be much appreciated.

mental ether
#

i fixed it

#

i just closed and reopened editor LMAO

hidden flicker
#

Why does my player move slower on slopes?

#

I also lose speed whenever I collide with a slope

rigid island
#

i mean isn't that how physics work

hidden flicker
#

i would like for it not to be

#

i thought setting drag to 0 would fix it - it didnt

rigid island
#

maybe use kinematic or character controller.

hidden flicker
#

doesn't work for the type of project / movement i'm working on :)

#

do you know why the bottom line of code doesn't fix things?

rigid island
#

is there a video online video that shows rb based controller fix for slopes?

hidden flicker
#

i've looked for some - can't find any that work

rigid island
#

you probably need to manually correct the velocity based no slope angle

hidden flicker
#

thought the bottom line of code would fix that - why doesn't it work?

rigid island
#

I wouldn't rely on that , i would at very least use a raycast

hidden flicker
#

not sure what you mean

rigid island
#

OnCollision enter only happens once

hidden flicker
#

OnCollisionStay?

rigid island
#

at very least.. or just a sphere cast for example if player is capsule, to get more area/width

hidden flicker
#

Here's the ground detection script and player structure, by the way

hidden flicker
rigid island
hidden flicker
#

if it detects a slope, what should it do

rigid island
#

correct the velocity accordingly

ashen kettle
fickle moth
#

Github related

Can someone please point me in the right direction!

What files from my unity project should i be pushing to git?

thick terrace
fickle moth
thick terrace
#

what on earth is in there? it should be a few small text files

fickle moth
#

lemme go see

#

should there be a packages folder be inside of the ProjectSettings folder?

thick terrace
#

yeah, that just has package specific config files

fickle moth
#

hmm im not seeing anything of a high file size within the ProjectSettings that would have stopped it , Maybe it was because i had tried commiting the Library folder with the ProjectSettings folder and thats why i got the file too big error

thick terrace
#

oh that's more likely

#

if you have previously committed library/temp/bin folders you may want to revert those commits so they don't exist in your git history, they can make your repo huge even if you're not using them

fickle moth
#

Thank you for helping me out!

I think ill go make a new repo and start from the beginning again!

If i use one of the .gitignore templates does that tell it to automatically filter out only what i would want from the project?

thick terrace
#

yeah, there's ones with all the common unity folders set up for you

fickle moth
ashen jasper
#

I mean like this. At the blue mark the player will start to follow the spline red is the path it goes on and the yellow and purple marks are the points if the player jumps that the z position gets pointed there and the green mark ends the spline path allowing the player to go back to free motion, The one in the middle is more of knowing which side he on now.

keen lantern
#

!code

tawny elkBOT
finite marlin
#

Can anyone help me with what may be the problem? I don't understand how that is the problem considering the name of my player console and first person controller is seraph. Anyone got any ideas on how to fix it? I was trying to implement a pick up system for some letters.

leaden ice
#

The names of your GameObjects are irrelevant for code

finite marlin
#

Appreciate it my bad.

leaden ice
timber locust
#

I want this shader to have a circular zone around the player that is normal while things farther away are distorted. I've been stuck on this for a couple days now.

#

currently everything is distorted, which is 50% there

leaden ice
#

Pass the player's screen space position into the shader then only apply the distortion effect of the distance is less than some radius. Use the step function

timber locust
#

dope ill try that, thank you

hazy pike
#

How doable is a perk system in a multiplayer game? These perks are unlockable and the players can use these perks in any server they join

#

bear in mind I am quite a beginner, this is my first game

somber nacelle
#

beginner
multiplayer game
these things are not compatible

hazy pike
somber nacelle
#

yes, start by learning what you are doing first before diving into your "dream game" or whatever. learn how the engine works, learn how to make a game. once you have that experience you will still struggle with multiplayer, but at least you'll understand what you are doing and why you are struggling

hazy pike
#

i am not really lost to be honest, I have used the engine before but I have just not made a game before

#

so far I have made things that are not really easy

lean sail
somber nacelle
#

you can give it a shot if you are really dead set on it, but expect to fail. or at the very least expect to not have made the game you are envisioning.
understanding how to create your game and how to network it is a huge undertaking

hazy pike
#

I'll see where it takes me and I dont really care if it succeeds or not, I just want to try

lean sail
#

also consider the fact that you asked about a perk system. Something that at the end of the day equates to adding 2 floats together, or even just simply running a method which contains the perk. The rest of your game is definitely gonna be questionable

spring creek
hazy pike
#

they work just as expected

ashen jasper
hazy pike
#

if the perk system is easier then oh well

#

I was just asking about the multiplayer part of it

cosmic rain
spring creek
merry stream
#

is there a reason that IPointerExit isnt called when an object is destroyed? how do I cause that to happen?

ashen jasper
#

Plus based on sonic superstars it ises a spline system

hazy pike
spring creek
lean sail
cosmic rain
ashen jasper
#

But Iโ€™m asking how it can be done

cosmic rain
hazy pike
somber nacelle
#

it is much harder to tack on multiplayer after the fact. if you have not been building your game in a way that would be friendly to multiplayer then you are going to have a very bad time

hazy pike
soft shard
#

Ah, multiplayer... I am on my 4th rewrite of my multiplayer code so far, even with pretty good architecture, its still a big challenge to optimize net code and gameplay, and we havnt even gotten to security management yet

cosmic rain
# hazy pike no I still haven't

Then maybe do that before implementing other systems, but really I agree with the rest of the people that you should start sorry a single player.

lean sail
#

Just saying, i had 9 years of coding experience and started with a mutliplayer game as my first project. I ditched it because it was too much.

latent latch
somber nacelle
#

i'm like 6 months into a multiplayer project and i already know i'm going to have to go back and rewrite a lot of stuff and i already had a lot of experience with making stuff in unity before i started it

hazy pike
latent latch
#

I raged at my item looter multiplayer project

#

making a multiplayer shooter is like 1000 times easier even if you need to deal more with latency

hazy pike
#

I am confident that this idea in my mind has a chance so I won't go back unless its really like... impossible to me.

latent latch
#

will probably tackle that project again eventually but too much databasing for me

hazy pike
#

but anyways, thank you guys for the heads up. Now I know that it would be normal when I feel like its hard

spring creek
merry stream
#

since event system is being destroyed i assume

#

nvm, its because another object is being destroyed beforehand

latent latch
cloud python
#

I'm starting to feel alright during my break here

long scarab
#

Hey there, I'm trying to link some sfx to a heat ray weapon I've made. on mouse click, it should play the 1st section of the clip once, then loop the 2nd/middle section while mouse button is still pressed. Once the mouse button is released, exit the loop and play 3rd clip where the sound releases & fades away.

Is there a way to do this other than splitting the sound effect into 3 separate files?

soft shard
long scarab
#

thanks for the suggestion

merry stream
#

How can I make the seperator line "full" with richtext

#

instead of having gaps between

rigid island
merry stream
rigid island
#

thats dependening on the font, idk if you can crunch the characters together without making a font variant with that setting and try applying that variance

soft shard
rigid island
chilly surge
#

Somewhat related, is there a way to provide rich text to UGUI text/TMP without having to deal with their rich text syntax?

#

Eg if you already have to do some form of parsing yourself like markdown, it'd be nice to be able to directly convert the AST and supply them, than to do another roundtrip.

fickle moth
#

Can someone please help me with github?

Ive spent a total of like 11 hours now trying to get it to work but every single time i try to push the project to github which takes like 3 hours it eventually throws an error because its trying to push the Library folder to github , I made sure the repo contained a .gitignore that was set up for unity and still it fails .... please im losing my sanity

rigid island
fickle moth
#

nevermind sorry i wasnt following the tutorial , am now

soft shard
chilly surge
# soft shard If I understand your question correctly, you can disable rich text formatting, u...

Yeah, let's say I get input from somewhere where the format isn't TMP/UGUI Text compatible, eg markdown, I have to do markdown string -> markdown AST -> TMP string, which TMP would do its own parsing from TMP string -> TMP AST -> finally displaying stuffs.
If there's a way to hook into the AST directly, I'd get to skip the whole middle step of going back to string, and just convert between the two ASTs. It's especially handy not having to deal with escape rules.

lean sail
#

what spawns the player? what spawns the enemies? Likely these scripts are related if not the same GameManager kind of script.
Whatever spawns the player can just keep the reference to them. Then provide it to the enemies whenever you need via some public function.

#

this is very vague, where do these events live if not on a script? it is bad if you make it bad

sly comet
#

I have a savegamemanager. If I load the save data it works. if i leave the scene and come back it breaks and can no longer load. Am I supposed to somehow read all the data into memory and sit on it until I need it? It seems I can only load files once.

fervent coyote
#

Hello! I have a ScriptableObject, called a map, that has data. It has to have a string that links it to a scene, I'd like to automate the creation process of maps by also creating the Scene automatically

I have the path + name set up, but I don't know how to actually make one... so is there a function I could use to create a scene on the ScriptableObject's creation??
Here's what I tried, didn't work... Maybe it'll give you an idea of what I'd like?

EditorSceneManager.SaveScene(EditorSceneManager.NewScene(NewSceneSetup.EmptyScene), path);

lean sail
fervent coyote
fervent coyote
#

Doesn't work...
(I know I used OnValidate, only because OnAwake doesn't work for path reasons)

glass rapids
#

can I ask one of you a question about learning Unity

fervent coyote
#
{
    //Create variables
    string nameAsset = name.Replace("Map_", "").Replace(".asset", "");
    string path = AssetDatabase.GetAssetPath(this).Replace(name + ".asset", "");
    if (_Scene != "")
    {
        _Scene = "Scene_" + nameAsset;
        AssetDatabase.RenameAsset(path + _Scene + ".unity", _Scene + ".unity");
        return;
    }
    var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
    EditorSceneManager.SaveScene(scene, path + "/" + nameAsset);
    EditorSceneManager.CloseScene(scene, true);
}```This is what I used
thin aurora
tawny elkBOT
#

:teacher: Unity Learn โ†—

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

slim gate
#

Not sure if this is the right place to ask cause its not technically code itself:
I have a question about DataPath and PersitentDataPath:

I do not quite understand the difference between them, from what I understand PersitantDataPath points to some folder like "AppData" while DataPath points to the DataFolder in your game.

I am using DataPath right now for loading in textures for a texture-pack system, that works fine.

Now I wanna implement a save system and it sounds like I should save settings/ saveFiles in PeristantDataPath, but why is DataPath not peristent? Files saved there will not stay after play is over? Why is one "persistent" and the other not?

lilac lance
#

Hi everyone. Can somebody help me with animation for my dyplome game? It's a basic thing, but I'm a beginner and can't solve my problem. Question in "Artist tools -> animation" branch

knotty sun
slim gate
knotty sun
#

in the Editor. Have you tried in a build?

slim gate
#

yep

#

projectName_Data

#

in the build

#

Thats where DataPath points to in a build

lean sail
slim gate
#

In engine it points simply to Assets

#

Ohhh

#

So I guess the main difference is that its read-only?

#

That would explain why it works for me, cause the texture-pack is placed in there manually and reading it works

#

I havent tried writing anything there yet

knotty sun
#

it may work for a windows build. it will not for an Android or WebGl build

lean sail
slim gate
#

So I guess I should use persitentDataPath for my usecase?

Putting a texture pack folder in
And saving settings/ savegame

knotty sun
#

if you want the texture pack included in the build use streamingAssetsPath

slim gate
#

no just for players to add their own if they want

#

It overwrites any texture in the game if it has the correct name

knotty sun
#

then persistentDataPath is the way to go

slim gate
#

Cool! Thanks alot!

#

appreciate the help

gritty monolith
#

Hi, im trying to figure out how to create a nativeArray from a pointer using NativeArrayUnsafeUtility but all I get is "Object reference not set to an instance of an object" error

            NativeArray<int> testArray = new(1, Allocator.Temp);
            testArray[0] = 12;

            void* pointer = NativeArrayUnsafeUtility.GetUnsafePtr(testArray);

            NativeArray<int> recreatedArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(
                                      pointer, testArray.Length, Allocator.Temp);

            Debug.Log(testArray[0]);//12
            Debug.Log(recreatedArray[0]);//Object reference not set to an instance of an object
cosmic rain
#

The last debug log?

fervent furnace
gritty monolith
gritty monolith
versed loom
#

If i have a string (e.g Something is <b>blue</b>) and I want to remove <b> and </b>. Is regex.replace more performant than doing a loop thru a stringbuilder and then remove the substrings by hand?

thin aurora
#

Regex will always be worse, but nowadays Regex can be code generated although I doubt Unity supports it

#

But if you strictly want to remove <b> or </b>, why not use a regular string.Replace?

#

@versed loom

lean sail
versed loom
#

i want to remove all <something> </something> substrigs

#

mb i didnt say that

thin aurora
#

Do you do this often or is this just once?

versed loom
#

once

thin aurora
#

If you do this once you can also just use a Regex

versed loom
#

and in an editor script

thin aurora
#

But in the same way just iterating a string and looking for the characters to remove isn't that hard either

versed loom
#

yea true

thin aurora
#

If your tags contain multiple characters add + after the w

versed loom
#

thanks ๐Ÿ˜„

languid hound
#

I'm tinkering with sprites and I was wondering
I have an atlas and I've sliced the sprites so now there's a bunch of sub-sprites

#

How can I through code get the UV coordinates of the subsprite on the atlas

#

There's the UV property but it's an array of vector2s

languid hound
#

Wait I suppose I could potentially divide the x by the width and the y by the height

leaden ice
dry obsidian
#

so... i want to make a script that gets the average normal direction of the ground in a sperical area around my player.. im aware you can access all normals of the mesh you've accesed via raycast & use the world position of the normal to determine if its within range, however, this would have to loop through all the normals on the mesh each frame, and that doesnt seem very smart resource wise. is there a way to simply get all faces within an area regardless of face orientation or parent mesh?

latent latch
#

loop through the normals on the mesh each frame

lunar python
#

hi everyone, can someone help me with climbing wall in 2d platformer. I know this sounds pretty basics but I want to add velocity to player when they are climbing using 'W' and 'S', and subtract an amount of velocity from player when they're stop pressing buttons. I dont want Stop Climb to set vertical velocity to 0 as it is negating all other forces including jumping. I have tried adding a variable that keeps the lastVerticalVelocity applied, however when the the player is hitting against wall, their velocity is now 0, and the lastVerticalVelocity isn't correct anymore. Is there anyway to achieve this wall climbing mechanics?

leaden ice
lunar python
#

I haven't seen a tutorial that makes wall climbing without setting velocity to 0 on stop

tawny gale
#

Anyone has made modding avaible in their game? Not just adding new visuals to the game or adding new assets more llike adding plugins and new levels or enemies if anyone as can I send ask some questions

dry obsidian
leaden ice
#

Or also try the inverse ray when there's no hit

dry obsidian
lilac lance
#

!code

tawny elkBOT
lilac lance
sly comet
thick terrace
latent latch
#

ya got a lot of stuff going there, why dont you break it down for us and tell us what part is breaking

sly comet
#

Im heading into work rn, probably should have waited to bump this. Basically I have objects that use the load method and it works great. If i leave the scene then come back it errors out even tho it was perfect the first time. I think it was saying filePath is null. Ill have to look again after work. Thanks

#

I was thinking of removing .dat from the files to make it all easier.

thick terrace
#

but it's hard to say what else is going wrong without seeing the error/logs

cosmic rain
tawny elkBOT
thin aurora
fickle obsidian
#

oh okay

knotty sun
#

And you were told where to post, which was not here

fickle obsidian
#

my bad New here sorry

#

This was a active channel so yea

thin aurora
#

Active channel != correct channel ๐Ÿ˜Ž

lunar python
#

never adding it to my future game

knotty sun
fickle obsidian
thin aurora
#

No, I don't do mobile stuff. This is one of the reasons why channels are divided

fickle obsidian
#

oh okay my bad

signal ridge
#

Is there a straight forward way to showcase 3D items (gameObject) set in code or inspector in the scene view ? Currently I have a OnDrawGizmos in use , but the children down the line do not get wireframed unlike the parent. (Tried protected on parent and sending it from children and also a function that would change it seperately )

leaden ice
#

And you seem to be mixing up parent and child GameObjects with parent and child classes in C#

signal ridge
# leaden ice It's confusing what you're talking about. You said "I have a OnDrawGizmos in use...

Sorry, yes so the parent is lets say Item and then child is Tool : Item , but then the Item gameObject could be one mesh while the Tool is assembled together by two pieces. So im sending the assembled piece to parent so it could be rendered right . But it doesnt get sent to the OnDrawGizmos before i press start.

    [SerializeField]
    protected GameObject itemModel; // The 3D model of the item

    void OnDrawGizmos()
    {
        if (itemModel != null)
        { // ColourByTag script in Utilities
            Gizmos.color = ColorUtility.Instance.GetColorByTag("item"); // Choose a visible color
            Gizmos.DrawWireMesh(
                itemModel.GetComponent<MeshFilter>().sharedMesh,
                transform.position,
                transform.rotation,
                transform.lossyScale * scale
            );
        }
    }
#

And for test i tried in the child this way at the moment (tried start too)

    private void Reset() // Called in the editor when the component is added
    {
        if (itemModel == null)
        {
            itemModel = Instantiate(toolModel, transform.position, transform.rotation, transform);
            itemModel.transform.localScale = Vector3.one;
        }
    }

leaden yoke
#

i want to add characters in unity and when in first person you can see your hands/body. and id its multiplayer i want others to see my character aswell. can someone tell me how or send me a video on how to do this

thick terrace
signal ridge
latent latch
#

for gizmos I usually just have some manager singleton with a single draw method and let all my objects access that instead

solar wigeon
dusky fiber
#

need help to create a good fnaf NavMesh AI (dm for more details if you want to help me)

wide dock
solar wigeon
#

ok

#

here

thick terrace
wide dock
#

Also if (dashes < maxDashCount) is most likely causing the issue. it should be only wrapped around the first inner if statement (timer)

wide dock
# solar wigeon what do you mean
private void Update()
{
    if (dashes < maxDashCount) 
    {
        timer += Time.deltaTime;
        if (timer > cooldownTime)
        {
            dashes += 1;
            timer -= cooldownTime;
        }
    }

    if (Input.GetKeyDown(DashKey) && dashes > 0)
    {
        dashes -= 1;
        UpdateUI();
        Debug.Log(dashes);
        Dash();
    }
    ...        
}```
#

There's only a reason for the timer to be updated if your current dash count is lower than the max count allowed

solar wigeon
#

so how do i wrap it ?

wide dock
#

Literally the way I just did.

leaden ice
#

I don't think that's how I had it in my sample code I shared with you yesterday

dusky fiber
#

If anyone here knows how to work with unitys NavMesh system and can help me make a good fnaf animatronic ai then please dm me (I got some code ready)

leaden ice
#

Yeah it's not

solar wigeon
leaden ice
#

in fact you put almost all of your functions inside Update @solar wigeon

#

you screwed up all the brackets basically

leaden ice
#

it's unclear what you mean by "sending it to the parent"

solar wigeon
lilac lance
solar wigeon
#

can u guys tell how to implemet ui as an array
https://gdl.space/enelahesed.cpp
DashChance[i].SetActive(dashes >= i); except of being SetActive i want it to be IsInteractable

leaden ice
#

We went over this yesterday too

#

Remember your old code where you were setting interactable = true or false

#

you do it that way

#

You need to have an array of Image or Selectable though if you want that

#

Like you had before

solar wigeon
#

oh ok ๐Ÿ™‚

dark tide
#

is there a way to get a pixel of a rendertexture from a mouse click?

gray mural
dark tide
#

wait- what's cross-posting?

gray mural
gray mural
dark tide
#

sorry-

#

I saw that a discussion was already going on in unity talk after I had posted it

#

and then I thought maybe code-general would be a better place

#

I'll go delete that comment in unity talk :D

gray mural
dark tide
#

done!

#

yeah makes sense I guess xD anyway, i don't really know how to use texture2d.getpixel with a rendertexture...

gray mural
#

Implement it. If there's something you don't understand about it or the answer doesn't fully achieve your objective, ask an another question here.

dark tide
#

ok...

#

so what I've got is a compute shader running conway's game of life on a render texture, and I would like to have the ability to make cells that I click on become alive.

gray mural
dark tide
#

alright :/ I'm sure I can figure it out

gray mural
#

And I'm sure you can achieve that using that link.

dark tide
#

by using that question-

#

yeah

gray mural
dark tide
#

anyway, thanks!

dusky lake
#

Is there a way to mask 3d objects with a 2d image without a shader?

#

I have a grid of objects in a scrollrect and they peek out of the scrollrect bounds

leaden ice
#

Then it will be masked normally with UI mask

dusky lake
#

as its for mobile i want to prevent additional cameras

leaden ice
#

I doubt you'll be able to do something without a custom shader then

azure heath
#

I've got a button that swaps out with another button when it's pressed, and vice versa. But when I press it, both buttons get activated, as if I tapped it twice. This doesn't happen when the buttons aren't overlapping. Any thoughts?

#

I only click it once at a time there until the end where I spam it

gray mural
#

Although not sure whether it's the most appropriate solution

#

Also, that's a normal button, right? It should be pressed when the button is released, which shouldn't activate the 2nd button.

#

Could you perhaps provide more context how you activate them?

clever lagoon
#

I like @gray mural 's idea of changing the sprite tho- avoid that kinda "both get clicked" stuff all together.

knotty sun
#

!code

tawny elkBOT
red dust
#

Hey all, been working on this problem all morning and figured Id see if anyone had any advice for me

So I'm realizing I made a slight mistake in my use of Scriptable Objects for the design I'm going for xP

basically I have an abstract class SpellSO, and things like ProjectileSpellSO and BarrierSpellSO that inherit from it, and I put the logic for casting the spells into that, hooking it up to my players SpellManager. This works perfectly fine if it was only the player casting these spells, since the player would be the only one accessing any of the functions in the scriptable objects.

but my plan is to let my EnemySpellManager hold the exact same spells to cast, which means things like castPerSecond start getting shared between my player and the enemies. tbh its kind of hilarious and might make a fun mechanic, but for now its something I need to fix.

I was planning to change the spell SOs to pure data containers for things like the prefab or any numbers it needs like damage and mp cost, and then move all the methods in those SO's to the SpellManagers, but I wanted to see if there was a better way to handle it

leaden ice
#

It's also unclear what benefit you get from inheritance here

#

ProjectileSpellSO what's better about this vs just having a SpellType enum on the SpellSO?

#

If you get rid of inheritance it becomes much easier to manage the actual SO assets in your assets folder

red dust
#

right now I have 2 types, Projectile and Barrier. the base SpellSO has basics like mpCost and spellName, with abstract methods for the CastPressed() CastReleased(), while the individuals are holding the specifics like projectileSpeed or barrierDuration that the others wouldnt have a use for, as well as implementing their own CastPressed or CastReleased stuff

#

plan is to add more like MartialSpells, SupportSpells, so this was how it made sense for me to break it up xP I'm new to this so Im sure it needs work

#

I mean I guess I could use an enum, and then switch states under the CastPressed etc, is that the suggestion?

vapid lynx
#

How do i go about diong gpu instancing for this?

fervent coyote
#

Hey, could anyone help me figure out how to create an empty scene and save it to the assets folder? Its for a ScriptableObject

#

Did someone @ me?

fervent coyote
#

Yes, when I create a new ScriptableObject, I'd like to automatically create a scene, pair it with the ScriptableObject, and save it to the assets

#

Uh, is there a way to use this method to create a completely empty scene?

fervent coyote
#

Create an empty new Scene at runtime with the given name.
It needs to be in the editor, I've also already tried this

somber nacelle
#

did you read the entire page?

fervent coyote
#

Okay, that... works

#

Thanks

#

Well, it does work, but only if one scene is open

somber nacelle
#

the open scenes need to all be saved in order to create a new scene

#

or rather, there cannot already be an untitled/unsaved scene

fervent coyote
#

Thing is they're all saved is the issue

somber nacelle
#

including the one you just created?

fervent coyote
#

No? Hmm

vapid lynx
#
{
    for (int x = 0; x < size; x++)
    {
        float rngTree = UnityEngine.Random.Range(0f, range);
        worldX = meshPosition.x + x;
        worldZ = meshPosition.z + y;

        if (treeNoise[x, y] < UnityEngine.Random.Range(0f, 0.5f))
        {

            if (heightMap[x, y] > 5)
            {
                Vector3 pos = new Vector3(worldX, heightMap[x, y], worldZ);
                Quaternion rot = Quaternion.identity;
                Vector3 scale = Vector3.one * 1;
                matrices.Add(Matrix4x4.TRS(pos, rot, scale));
                index++;
            }

        }
        if (treeNoise[x, y] < rngTree)
        {
           if (heightMap[x,y] > 5) { 
                GameObject newTree = Instantiate(treePrefab, new Vector3(worldX, heightMap[x,y], worldZ), Quaternion.identity);
                newTree.transform.parent = treesChunk.transform;

           }
        }
    }
}
Graphics.DrawMeshInstanced(grassMesh, 0, grassMaterial, matrices);```

im trying to do gpu instancing for grass
#

however it wont show?

#

i saw somwhere that u had to chekc the gpu instancing

#

i did do that but it doesnt help

fervent coyote
#

FUFKC

#

ALL MY WORK

#

GONE

somber nacelle
#

what did you do? save over the scene you were already working on with one of your new empty scenes?
if that is the case, surely you have some sort of version control so you can just revert the change, right?

fervent coyote
#

No

#

I don't

#

I'm fucked

#

It accidently overwrote

#

Everything

#

All my maps

#

It created new scenes

#

And just
Saved over them

#

There's no way to revert this is there

#

I have a built version a few days ago

#

I could revert the build, yeah?

#

I could get the scenes from the build

#

I would lose progress, sure, but it's better than losing everything

somber nacelle
#

well let this be a lesson to always use version control

#

and if it is possible to get the entire scenes from your build, it would be done using tools that are not allowed to be discussed here because it is against server rules to discuss decompiling or asset ripping

fervent coyote
#

Okay, I'm soryr

#

I'm so sorry

somber nacelle
#

not a code question. see the documentation pinned in #๐Ÿ“ฒโ”ƒui-ux to learn how to anchor and scale your UI

naive swallow
#

Some lessons are written in blood

fervent coyote
#

I already use git, but nothing for like

#

Maybe a few weeks

#

But too much stuff would be lost regardless

#

A new level, a new city-

naive swallow
#

Then count yourself lucky you have something from at least that far back and the lesson becomes "Commit more often"

fervent coyote
#

When I mean everything, I mean everything

naive swallow
#

and definitely before doing something potentially destructive

indigo drift
#

Im making a big project so yeah I uhhh donโ€™t wanna demolish this accidentally

#

๐Ÿ˜ญ

lean sail
toxic fjord
#

Hello I currently am implementing combat animations into my game and have the input working for a punch attack but when my animation is transitioning back to the idle state my character just gets stuck on the last frame of my punch attack and can not go back to the idle state. I keep trying to reset the trigger code for my animation back to false after it is turned on but it wont. any advice?

indigo drift
#

Swag

indigo drift
#

Iโ€™ve only done vscode things on github but unity files are like massive

merry stream
#

anyone kinow what could be causing this? When I click on the text, i doesn't take me to the file where the issue is located so I have no clue what's going on

#

nothing seems to be broken though, just keep getting the error

lean sail
lean sail
indigo drift
#

Uhh I donโ€™t remember, let me try again I removed the git stuff a while ago when I couldnโ€™t figure it out

merry stream
indigo drift
#

Anyway guys if I happen to make like a really big switch statement will that like be bad for performance or something or will it not matter I canโ€™t think of anything more efficient for this thing Iโ€™m doing

lean sail
merry stream
#

also I do the same for other derived classes and have no issue

lean sail
lean sail
merry stream
#

i use "new" so I dont have to cast the variable every time

somber nacelle
#

new just allows you to create another separate variable of the same name and just hides the base class's variable of that name

lean sail
#

and are separate

merry stream
#

ah i see

#

should I just remove it and cast instead?

#

for context, it is my item system

#

so say I have an equipmentInstance, it references some baseItem SO equipment

lean sail
#

the point of overriding is so you dont need to cast, though maybe i am misunderstanding what you're doing

merry stream
#

ItemInstance has baseItem with type Item, EquipmentInstance has baseItem with type Equipment etc

#

and Equipment is derived from Item

lean sail
merry stream
#

say I have an equipmentInstance, i would have to cast the baseItem since it would be of type Item

finite ferry
#

I got a problem, but first here's the context:

I recently implemented these things in my Unity project:

  • Scriptable objects that holds information about the GameObject they're attached to ("attached" as: in variables on another script already on the gameobjects)

  • A public abstract superclass "ClassResource" that doesn't derive from MonoBehaviour:
    This class is supposed to hold the base information every scriptable object is supposed to have, i.e strings holding the descriptions

  • Public subclasses that derive from the superclass:
    One example of a subclass is "ClassCraftable", this class will hold info such as the recipe for how to craft the object. It's a subclass since not all objects are supposed to be craftable. But those that are will have both the base info (from the superclass "ClassResource") and the crafting info (from the subclass, in this case "ClassCraftable").


Now, my problem is with the scriptable objects:

I have a public variable of type ClassResource (the superclass) in the scriptable object script and this variable is supposed to hold whatever subclass I decide the scriptable object should "be", like maybe a craftable resource (in that case I'd choose the ClassCraftable script).

And this works, except for in the inspector. The field shows up on the scriptable objects, but when I open the selection window, by clicking the circle with a dot, nothing shows up (and I can't drag-and-drop the scripts either). I want to see the subclass scripts there, like the "ClassCraftable" script, or at least be able to drag-and-drop.

Is it possible or do I have to make like an if-statement with else-ifs for every subclass manually?
(I'd guess it has to do with the fact that the subclasses aren't connected to any Gameobjects or something along those lines)

#

(I hope this is clear enough. Just felt that context was needed)

indigo drift
# lean sail "for this thing Iโ€™m doing" describe the use case and itll be possible for people...

Well Iโ€™m asking if large switch statements in general are bad in performance or donโ€™t have an effect. Also I think the point of someone asking if itโ€™s bad is because they donโ€™t know whether it is or not lmfao.

But anyway, Iโ€™m making multiple different methods that are abilities in a turn-based combat kinda system, and Iโ€™m planning on using a list of strings to mix and match the abilities each character has. So like you pick out one of the strings and then itโ€™ll run the switch and run the method corresponding to the ability.

If thereโ€™s a better thing to use Iโ€™m curious about it, but if itโ€™s not super detrimental to performance, then Iโ€™ll probably just go with that plan anyway

spring creek
indigo drift
#

Itโ€™s not like Iโ€™m a triple A studio or something so not having maximum possible efficiency isnโ€™t gonna kill me but learning different approaches is still cool if you or someone else has a suggestion

#

Okay ๐Ÿ‘

spring creek
#

For your use case, consider a dictionary and just get the string as a key, with the ability as the value
The ability would have its own method to run

craggy oyster
#

no switch statements are not bad for performance unless youre repeating code

craggy oyster
#

repeating and expensive calls are the key to bad performance

indigo drift
#

Okay then yeah I think a switch statement will be fine because itโ€™s a thing that runs exactly once each time you use it, but Iโ€™ll try out the dictionary too!

heavy bone
#

i have this code and all im trying to do is place a 2dBoxCollider (floatingObject) within another 2DBoxCollider called areaCollider. Im trying to make it so that the blocks i place have to be fully enclosed in this collider in order to return true. Can anyone please help me out?

leaden ice
finite ferry
lean sail
lean sail
sly comet
#

I have a savegamemanager object that persists through every scene as a dont destroy singleton thing. It needs to be passed as a parameter to an object after the first scene, but its not in my hierarchy. How do I pass it?

thick terrace
sly comet
thick terrace
#

alright well that's a field not a parameter ๐Ÿ˜›

#

if it's already a singleton, the easy way is to either add a static Instance property to the singleton you can look it up from, or just to do FindObjectOfType since you know it's in the scene already

sly comet
#

I have the instance property on it, I'm not exactly sure what to do with it tho

jagged junco
#

Question: Is there some obvious way I am missing to search for objects inside a specific scene? This is in the context of stacked scenes for a networked game, but the question applies to additive scenes as well. Nearest I can tell, you have to do a FindObjectsOfType or similar which returns results across all scenes, then filter the results out. Seems inefficient especially if you have several copies of the same scene open server-side.

thick terrace
late lion
late lion
#

I win ๐Ÿ˜Ž

jagged junco
#

And that will be scoped only to the scene of the object which calls it?

thick terrace
#

it's an instance method, you can get the scene of a specific object with gameObject.scene and call it from there

#

so yes, it's only the root objects from that scene

sly comet
#

saveGameManager = SaveGameManager.instance;

'SaveGameManager.instance' is inaccessible due to its protection level

#
public class SaveGameManager : MonoBehaviour
{
    private static SaveGameManager instance;
    private string savePath;
    private const string encryptionKeyPlayerPrefsKey = "EncryptionKey";
    private string encryptionKey;
    public double totalOverallTime;
    public int levelsCleared;

    private void Awake()
    {
        // Singleton pattern
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);```
thick terrace
#

you could just make instance public, but i'd suggest making a public property so other script can't accidentally set it, like public static SaveGameManager Instance => instance;

jagged junco
sly comet
# thick terrace you could just make `instance` public, but i'd suggest making a public property ...

public static SaveGameManager Instance => Instance;

StackOverflowException: The requested operation caused a stack overflow.
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)
SaveGameManager.get_Instance () (at Assets/Scripts/SaveGameManager.cs:10)

jagged junco
#

Lower-case i

#

You're self-referencing Instance, causing an infinite loop

#

public static SaveGameManager Instance => instance;

sly comet
#

it won't let me, says it doesn't exist. Do I just need to state it just above this one?

thick terrace
#

add this to the existing class, don't delete the old instance

sly comet
#
public class SaveGameManager : MonoBehaviour
{
    
    public static SaveGameManager Instance => instance;
    private string savePath;
    private const string encryptionKeyPlayerPrefsKey = "EncryptionKey";
    private string encryptionKey;
    public double totalOverallTime;
    public int levelsCleared;

    private void Awake()
    {

        DontDestroyOnLoad(gameObject);```
#

The name 'instance' does not exist in the current context

thick terrace
#

you deleted instance, put it back ๐Ÿ˜„

#

it was there in the last snippet

#

or if you want it in one line, use public static SaveGameManager Instance { get; private set; } instead

sly comet
#

got it

jagged junco
#

Here's how I do all my singleton stuff:

#region Singleton
/// <summary>
/// Singleton accessor
/// </summary>
public static FooBar Instance { get; private set; }
#endregion
#

Then in Awake():

private void Awake()
{
    if (Instance != null && Instance != this)
    {
        Destroy(gameObject);
    }
    else
    {
        Instance = this;
    }
}
#

Cheap and easy

sly comet
#

I'm like 1 week in and no proper schooling on it so its rough sometimes lol

#

but if I can get menus and save/load working I have a fully functional fun game

#

so I'm pushing through really hard lol

#

appreciate the help

#

gpt told me to do what you have in the awake method

#

doesn't work for me though since my Instance is read only which is nice

#

as long as my first scene has the singleton it should always exist

jagged junco
#

What are you using for menus? GameObjects in a scene or the UI Toolkit approach?

sly comet
#

ui objects and gameobjects

#

getting a null error. once I hit start i go from mainmenu scene to levelselect scene

#

once i go to levelselect scene i get null

NullReferenceException: Object reference not set to an instance of an object
LevelSelectScreen.Start () (at Assets/Scripts/LevelSelectScreen.cs:26)

#
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

public class LevelSelectScreen : MonoBehaviour
{
    public GameObject buttonPrefab;
    public Transform buttonContainer;
    private SaveGameManager saveGameManager; // Reference to the SaveGameManager

    void Start()
    {
        saveGameManager = SaveGameManager.Instance;

        // Calculate the vertical offset between buttons
        float buttonSpacing = 220f; // Adjust this value as needed

        // Set the initial vertical position for the first button
        float initialYPosition = 350f; // Adjust this value to set the desired initial height

        // Iterate through levels 1 to 30
        for (int levelNumber = 1; levelNumber <= 30; levelNumber++)
        {
            string sceneName = "Level " + levelNumber;
            LevelData levelData = saveGameManager.LoadLevelData(sceneName);```
#

its still there

#

and you see in that code I reference it saveGameManager = SaveGameManager.Instance;

thick terrace
#

the value of Instance is probably not being set then, what did you end up with in that class?

sly comet
#

sorry I'm not sure I understand your question.

thick terrace
#

what did you change in SaveGameManager

sly comet
#
using UnityEngine;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine.SceneManagement;

public class SaveGameManager : MonoBehaviour
{

    private static SaveGameManager instance;
    public static SaveGameManager Instance => instance;
    private string savePath;
    private const string encryptionKeyPlayerPrefsKey = "EncryptionKey";
    private string encryptionKey;
    public double totalOverallTime;
    public int levelsCleared;

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);```
thick terrace
#

can you show where instance is being set?

sly comet
#

do I have to set it in the savegamemanager as well?

thick terrace
#

it's not being set anywhere, you're only referencing the value from elsewhere, so the value is always null

#

yeah, you need to set it in Awake

sly comet
#

instance = Instance;

#

like this in awake?

thick terrace
#

it's null, so that won't do anything

#

look at the example TactiFail posted

sly comet
#

good point

#
public class SaveGameManager : MonoBehaviour
{

    private static SaveGameManager instance;
    public static SaveGameManager Instance => instance;
    private string savePath;
    private const string encryptionKeyPlayerPrefsKey = "EncryptionKey";
    private string encryptionKey;
    public double totalOverallTime;
    public int levelsCleared;

    private void Awake()
    {
        instance = this;

        DontDestroyOnLoad(gameObject);```
#

logically this doesn't make sense to me though, because if I'm setting instance = this in awake, when do the fields above happen?

#

because I'm guessing
Instance => instance
happens before
instance = this;

thick terrace
#

before awake, but => doesn't mean assignment, it means it fetches the value from the private instance every time you write Instance

sly comet
#

ah it's a shortcut

#

or a link

thick terrace
#

it's short for public static SaveGameManager Instance { get { return instance; } }

cosmic rain
sly comet
#

YAY leveldata! thank you thank you thank you thank you

#

that's really good to know thanks ๐Ÿ™‚

#

it loads them multiple times too

#

soooooo happy thank you

#

I spent 3 hours trying to get the buttons to scroll lol idk if I'm cut out for a scrollbar I might just make them all appear on screen instead lmao

#

would be cool you can see all your pb times at once as well and take a screenshot. but that convo is for a #archived-game-design

thank you all so much for the help. I really appreciate it

thick terrace
#

glad to see it's working!

red dust
#

Woot, so it took a a few hours, but I managed to successfully uncouple my SpellManager properly to be used by both enemies and players, and then took all the functions from my spell scriptable objects and chucked it into the Spell Manager so they're holding solely the spell's data like mpCost and cooldown.

Right now the SpellManager has to currently do some checks between spell types to figure out which Casting methods to use, which makes that class a bit longer than I'd like, and it's only gonna grow as I try to add the other spell types I have in mind. But I'll leave refactoring that to another day. Today's goal was accomplished: make sure the player and enemies don't interfere with each other's spellcasting, and that enough for me for now xD

soft shard
red dust
#

Honestly not at all xD I'm still new to this so now I'm afraid if I try to offload it from the SpellManager itself into somewhere else that I'll just put it in another dumb place xD

The current plan is to have 4 spell types, so Projectile, Melee, Barrier, Support. Right now the SpellManager has functions for CastPressed CastHeld and Cast Released, and then each of those functions are checking if the SpellSO being triggered inherits into a ProjectileSpell or a BarrierSpell to check what it needs to do, then it fires the shot or makes the barrier. From there the projectile or barrier handles itself.

The plan for now is to add the checks for the next two types to make sure they work how I want, then from there I'm not sure yet ๐Ÿ˜…

soft shard
# red dust Honestly not at all xD I'm still new to this so now I'm afraid if I try to offlo...

Im sure others might have ideas as well, though personally I would maybe have each of those types as interfaces with maybe a base ISpell, then you can make specific, generic or hybrid types (for example, a GenericProjectile : IProjectile or a specific SmokeGrenade : IProjectile or MissileSystem : IProjectile, or even a MissileShield : IProjectile, IBarrier if you wanted a shield you can throw, and then "deploys" on landing or something) - then your SpellsManager can have a list of those types or a List<ISpell>, your manager then doesnt need to know what the type is (so you wont need several checks), it can just call the interfaces Cast(), CastHold() etc, and the MissileSystem or MissileShield etc can decide how to handle the interfaces it uses

red dust
latent latch
#

My spell system is composed of just a single class, I just use enums to split behaviours

#

targeting is generally the only reason I feel to split the class up over doing pure composition

#

but my workaround is always include the max targeting params and just not use them if I don't need to

red dust
#

Basically how mine is now. The SpellManager is the class that handles all the logic taking in the Scriptable Objects to hold any values and effects

latent latch
#

The problem expanding the classes into their own classes is that sometimes you do want some of that functionality in those other classes. And, the more you divide these classes down, the more duplicated code you may end up having to do. So I think a heavier component approach with more comparison checking over polymorphic behaviour is the idea for these.

#

The downside is you may end up with some edge cases or some busted combinations but the fix to this is just don't make those spell combinations.

vague tundra
#

Anyone got a neat solution for managing the check for whether or not a coroutine has completed?

cosmic rain
vague tundra
#

Cheers, how might you go about setting that referrence value?

#

Hmm, I suppose the coroutine could set its own reference as its final breath... interesting

lean sail
cosmic rain
#

coroutine = StartCoroutine(Coroutine())

vague tundra
#

Mhm, but at what point would you set that ref to null?

cosmic rain
#

At the end of the coroutine

vague tundra
#

Snazzy, cheers

spiral yacht
#

does anyone have any pointers or resources for understanding manipulating this grid better, its a grid script which gets filled with cells and im trying to detect when another cell beside the current cell the function is currently checking for the conditions and see if it has the desired tag on the condition, i thought this should be correct but, doo doo brain moment ig,

#

this is all cells are, figured i should post it

lean sail
red dust
#

One last little refactor before I stop for the night xP

spiral yacht
#

i thought it would be as simple as adding another cell thingy and adding 1 to the x value but yeah

fervent furnace
#

do you know what the difference is between ++x and x++

#

or try to log

cell1==cell
spiral yacht
#

no idea all i know is ++ adds another increment or smthn like that, kinda forgor, i was looking into it the other night actually

fervent furnace
#

or what x++ actually does

spiral yacht
#

yeah no

#

the code isnt ++ right now though thats my bad for posting that, currently doing just x+1 in the code, that was just me seeing if thats whatt i was looking fro after i read about it a little

fervent furnace
spiral yacht
#

thank you

fervent furnace
#

btw you still need to rewrite the loop a little bit for accessing

array[x] and array[x+1]
```since you will get index out of bound if the length is not multiple of two
spiral yacht
spiral yacht
#

you mean like this? affirming I'm interpreting what you said to do right

#

just to be clear I didnt add cell2 cause of that, thats just to detect the other side of the cell I'm trying to do stuff on

fervent furnace
#

No, just accessing two different elements in an array

vital iris
fervent furnace
frail dust
#

I want to call a function using a broadcast from another script. If a variable is true in LaneManager script, then the function in EnemyMovement should be called. But I am facing this error: NullReferenceException: Object reference not set to an instance of an object in the line
"Lm.onEnemyRemoval.AddListener(ManageLanelessCars);"

If I check for LaneManager, it isnt null, but this line of AddListener is null somehow. Please help
(Scripts given below for reference)

https://pastecode.io/s/sy2ti73v --> EnemyMovement Script
https://pastecode.io/s/nkh097ft --> LaneManager Script

slim gate
#

did you put a Debug.Log in the Start after trying to find Lm?

#

to see if its null

fervent furnace
#

check if lm is null
then check if your custom unityevent is null

slim gate
#

I also dont use unity events, Id just use C# events/ delegates

#

but thats beside the point

thin aurora
broken nest
thin aurora
#

Again, share the whole exception. If you want to be helped you're going to have to specify where the error is

frail dust
#

Its a long ass code

thin aurora
#

Did you read my initial message?

frail dust
#

I edited so it would be easy for u to view

fervent furnace
#

how about your custom unity event? you have two things to check

thin aurora
#

Your logged exception will specify a line which is the line where it was thrown on.

#

Put in some effort in sharing the issue

thin aurora
#

Your Unity console would have logged the exception

frail dust
#

Oh that

thin aurora
#

Surely you know what that is?

#

So share the whole context from there

frail dust
thin aurora
#

EnemyMovement.cs:26

frail dust
#

The 26th line is what I shared

thin aurora
#

That is line 26 of that file

frail dust
#

Already in the links i mentioned above

thin aurora
#

There is no line 26 in the code you shared

frail dust
#

I cant display the whole code

thin aurora
#

Right, so for next time it would help a ton if this was specified more clearly

frail dust
#

Only written relevant info

thin aurora
#

Anyway, the only thing that can be null according to this would be either Lm or onEnemyRemoval

frail dust
#

Lm isnt null

frail dust
#

Lm is always present in the scene( as in gameobject)

broken nest
#

onEnemyRemoval might also be null

thin aurora
#

That doesn't matter

frail dust
#

But im not so sure about onEnemyRemoval

fervent furnace
#

so i told you to log it

thin aurora
frail dust
#

public class EnemyRemovalEvent : UnityEvent { }

I have declared it like this

frail dust
thin aurora
#

You mentioned this is the line that throws, so it's one of the two variables

#

But surely this is not the case then because you logged the value, right?

lean sail
#

why is that even a class ๐Ÿค”

thin aurora
#

So either it's an entirely different line or you didn't log it

broken nest
frail dust
#

OnEnemyRemoval:
UnityEngine.Debug:Log (object)
LaneManager:Start () (at Assets/Scripts/LaneManger.cs:90)

#

I debugged

#

this shows in console

thin aurora
#

Please share the whole code instead of cutting everything out

#

Or at least until like line 30

frail dust
#

Okay

fervent furnace
#

yes it is null, the class name is not logged

#

btw you can log

instance==null
frail dust
fervent furnace
#

otherwise if you log

$"hi i am {instance}"
```if the instance is null then you get "hi i am ", quite difficult to see
frail dust
#

I will be more clear. Actually Enemy Movement script is existing on various items, various instances. So I dont want to have a reference of it in LaneManager and call that function for every reference (Because I think it sounds tedious and not performance friendly). Also there is only 1 laneManager script in the whole scene. SO i thought lets give this AddListener attempt a try

broken nest
#

Looks like
FindObjectOfType<LaneManager>();
is not finding any objects of type LaneManager

frail dust
#

Otherwise my whole script wont be working

#

The spawning on lanes is dependent on that

#

So Lane Manager isnt null as I have debugged it

#

What might be the issue is in the Lm.onEnemyRemoval.AddListener(ManageLanelessCars); line

#

Because onEnemyRemoval is null in debug console

fervent furnace
#

so you need to create an instance

frail dust
#

In the original script I defined the class?

fervent furnace
#

before others access it

frail dust
#

or in the script in which function is called

#
    public static LaneManager Instance => _instance;


    public EnemyRemovalEvent onEnemyRemoval = new EnemyRemovalEvent();

    private void Awake()
    {
     

        if (_instance != null && _instance != this)
        {
            Destroy(gameObject);
            return;
        }
        _instance = this;
    }```
#

Like this?

knotty sun
knotty sun
#

Ok, so onEnemyRemoval is not serialized. you should add the [System.Serializable] attribute to your class definition

frail dust
#

and then? what do i serialize it with?

knotty sun
#

Unity will do that

fervent furnace
#

if the class is serializable the editor will create an instance for you

#

if you dont want to see it in inspector then you need to do this by yourself

frail dust
knotty sun
frail dust
#

nope

frail dust
fervent furnace
#

you code is mainly create a singleton

[System.Serializable]
public class ClassA{
  public int a;  
}

public class ClassB{
  public int b;
}

public ClassA classA;//you will see a fold out group in your inspector, and the instance of ClassA is created
public ClassB classB;//you wont see anything, just a declaration
frail dust
#

I got what i was doing wrong

#
onEnemyRemoval = new EnemyRemovalEvent();```
#

i just added this line and it fixed

knotty sun
#

Should not need that if EnemyRemovalEvent is Serializable

frail dust
#

I have items spawning on roads. Now if the roads get destroyed or move out of scene, I want the items to move along the road in the same speed out of the scene so It doesn't look absurd to the player. Any tips how do I achieve that? I tried writing a code of mine below but it doesn't work

    {


        GameObject removedLaneLeft = Lm.instantiatedLanesLeft[Lm.instantiatedLanesLeft.Count - 1];
        GameObject removedLaneRight = Lm.instantiatedLanesRight[Lm.instantiatedLanesRight.Count - 1];


        Collider2D leftLaneCollider = removedLaneLeft.GetComponent<Collider2D>();
        Collider2D rightLaneCollider = removedLaneRight.GetComponent<Collider2D>();


        foreach (GameObject i in items)
        {

            bool isWithinBoundsLeftLane = leftLaneCollider.bounds.Contains(i.transform.position);
            bool isWithinBoundsRightLane = rightLaneCollider.bounds.Contains(i.transform.position);

            if (isWithinBoundsLeftLane || isWithinBoundsRightLane)
            {
                Debug.Log("Speed changed");
                i.transform.position += new Vector3(0, ((Speed + 5f) * Time.deltaTime), 0);
            }
            else if (i.transform.position.x == mlp1 || i.transform.position.x == mlp2 || i.transform.position.x == mlp3 || i.transform.position.x == mlp4)
            {
                Debug.Log("Cars Destroyed");
                Destroy(i);
                items.Remove(i);
            }


        }```
frail dust
#

the objects are getting spawned from above the scene, scrolling downwards to the screen (out of the scene) which visually makes player feel as if the cars are moving (2D ). The items arent paired with anything. The items get spawned on random middle road positions and move downwards. Also Theres a pickup "LaneDecrease" which can be picked up by the player, so the lanes go downward the scene (instead of just scrolling infinite) and get destroyed. Eg: 4 lanes before, then 2 lanes.

So The items which were spawned on those lanes (the lanes which are destroyed) would look as if they are on the ground and not on roads. SO I want these items to either catch through the lane's speed and look as if all items are moving with lane outwards the scene. Or if the items spawned are not visually visible and they are the items on which no lane is present, then the items get destroyed simple

tawny gale
#

Hi anyone as implemented modding to their game. I'm trying to implement modding to mine I already can import asset bundles and it everything working but the problem u cant import scripts included in the asset that u created from the asset bundle. I'm trying to do some work arround this I already tried with making a assetbundlel with .txt and then try to compile but the probllem is I cant create the asset bundle with two assets (and I already tried to compile the code in and IDE then import it to unity) to then add it to the asset but I'm having a error that I cant add it to the asset. And I'm just lost does any one worked with modding that can help me?

ocean heath
#

Hello guys!
Is there any texture format in unity where can I store multiple samples per pixel?

thin aurora
#

This is a coding channel

ocean heath
#

Yeah that is why I ask, if there is any render texture class, which can store multiple samples.

acoustic laurel
#

Hey guys im super new to this and I've been stumpted on understanding player controls with cinemachine.

#

how exactly could this be replicated with cinemachine? More specifically, what tools/components are present in making the player follow the crosshair?

silver chasm
#

guys is it possible to integrate payment gateways in unity?

ocean heath
hybrid relic
kind cipher
#

Good morning. I'm having an issue with 'Parent Constraint' component.

I'm adding a source at runtime.

This is how I'm calculating the rotation offset (basically I'm wanting the object to keep its current rotation when grabbed by the Parent Constraint, and only rotate as parent rotates)

Vector3 CalculateRotationOffset(Transform transformA, Transform transformB)
{
    
    // Calculate rotation offset
    Quaternion rotationOffset = Quaternion.FromToRotation(transformB.forward, transformA.forward);
    Vector3 eulerRotationOffset = rotationOffset.eulerAngles;

    Debug.Log(eulerRotationOffset);
    return eulerRotationOffset;
}

I've also tried Quaternion.LookRotation or whatever that is. The look rotation it just rotates to some crazy new angle on grab. the FromToRotation method seems to zero out its rotation on grab.

Next thing I'm going to try (since documentation isn't very clear on the offsets), is converting the rotation to local rotation.

static matrix
#

can I change the color of individual letters in a Tmpro?

kind cipher
#

if you want more, and easier control, i think there are a few assets in asset store that let you do animations, and color changes and whatnot with TMP

static matrix
#

ah
well i'll probably just have three colors max at any given point so I can probably just use three text boxes for now

azure heath
azure heath
latent latch
#

oh you do want it to rotate with the parent constraint but undoing the constraint and reapplying the constraint to another is the problem?

#

try that

#

maybe with some rotatetowards if you need the lerp

#

and probably stick a parent constraint on something not moving? (well, unless you do need the parent to supply the position and not the rotation)

fickle moth
#

Does anyone got any info on something like a dependency visualizer?

Something simple, maybe node based that i can use to map systems out (purely for organization purposes)

clever lagoon
# azure heath The gameobject gets deactivated and the other one gets activated

That sounds like it SHOULD work without making the both click. Can you confirm you see it behaving as expected in the object hierarchy? (e.g. one of the button IS in fact always inactive, it just changes which one. also, better double check their state BEFORE clicking anything to confirm just one is enabled at start.)

fickle moth
#

Never mind found what i was looking for

static matrix
#

ooh what flowchart maker is this?

fickle moth
#

lemme find it for you

static matrix
#

also, I can't pass params to a button right?

#

ui button

fickle moth
#

i have no idea , i just found it

#

oh you mean within unity , nah not unless you specifically do it within a function i believe

static matrix
#

yeah
time to have 3 different functions for three different buttons that do the same thing but have to check a different value

fickle moth
#

you could have something hold the param and have whatever function access the holder when you call the function using the button

#

its janky but will get around not being able to pass params in with buttons thorough the inspector

static matrix
#

well yeah ofc you can just assign the value
but if it changes at runtime nothing you can do

latent latch
#

button with params doesnt make any sense. It's like how do you pass something just by clicking on it? You need some variable to store some previous value somewhere and read that inside of the button.

civic summit
#

I need some fresh view on a problem. I am making a board game and right now I move a player figurine just by teleporting it to the field dropped on the dice. How can I make a animation for movement (figurine steps on every next field before reaching its destination )and to make a method that runs logic to wait before animation is finished? Or how can I make it in the other way?

knotty sun
civic summit
slim gate
#

Should be easy with a simple script right?

#

Just move it there while moving the figure up/ down
where the highest height is the halfway point between two fields

knotty sun
#

I have no idea what you mean by that but, and I'm just guessing here, you do not need animation you just need something like a Coroutine implementing a MoveToward loop

slim gate
#

expert graphic of what i think he means

#

Like when moving a chess piece tile by tile

#

Or any boardgame

knotty sun
#

ok so what I said using a Bezier Curve

slim gate
#

I never did anything with bezier curves

knotty sun
#

look at your graphic, you have an array of start and end points, you just need a curve algo to get the movement between each one

slim gate
#

yeah makes sense

steady moat
#

I believe the easiest would be to have a height over distance function.

#

With an AnimationCurve that would be easy to implement.

knotty sun
#

would also work, there are many ways to skin this particular cat

gray mural
#

So the 2nd Button's click event gets activated instantly after the 1st button, which enabled the 2nd, is clicked

#

That's quite strange, I'd suppose

#

Consider waiting a frame before changing the buttons

firstButton.onClick.AddListener(ChangeButton);
secondButton.onClick.AddListener(ChangeButton);

private void ChangeButton()
{
    StartCoroutine(ChangeButtonCoroutine());

    IEnumerator ChangeButtonCoroutine()
    {
        yield return null; // wait a single frame

        // change buttons
    }
}
#

This should work, but I still wonder why the click event is triggered instantly ๐Ÿค”

leaden ice
#

Another option might be something like a custom OnPointerClick handler or OnPointerUp handler that consumes the event rather than letting it "bubble" down

gray mural
leaden ice
#

I don't think it's something you can do with Button.onClick

static matrix
#

is it possible to make it so ui takes up the same amount of screen space and has about the same positions irregardless of the resolution?
messing around with the canvas stuff has not seemed to work

leaden ice
#

It's possible to do so for some definition of space and position but not all definitions at once

static matrix
#

can I get the menu ui to look like this irregardless of the resolution?

#

(ignore the white squares, thats just what it looks like in not-play mode)

leaden ice
#

for example:

  • you can anchor an image to be 10 px from the right edge of the screen.

But this will not always be the same percentage of the screen, or the same distance from the left side of the screen

leaden ice
#

that's the problem

static matrix
#

let me try and be more specific one sec

leaden ice
#

not code

static matrix
#

sure ill move there

crisp bronze
#

Anyone encounter this issue when installing the Timeline package?

edgy stump
#

How to set font for each one option in dropdown unity?

simple egret
#

The dropdown has a disabled "template" object that is used to construct options, you can modify that

edgy stump
simple egret
#

The ordering of options in the .options list will be identical to the ordering of the instantiated child GameObjects for each option. From there with the parent container of all options, get the specific child option object by index, retrieve its Text component and change the font

tall scroll
#

so I'm in the need of some form of cone-cast, and google isn't helping a ton. if it was a simple LOS thing then I could use a trigger/collider to manage it, but I need to find the nearest point to the player within a cone which could be on a wall or the floor or something. Any ideas of what to look for or adapt or create to make that possible?

rigid island
twilit scaffold
#

Every time i populate or change one of these prefab entries, it does a Domain Reload, which takes a while. Is it expected that it does that? I do not seem to recall that in the past.

tall scroll
rigid island
#

could use just use a trigger then on OnTriggerEnter fire a ray for precision

twilit scaffold
tall scroll
#

(humor my bad drawing lol) not all of the rays here would connect but some would definitely be closer than others. Can't easily raycast based on the trigger enter because the centre of the wall almost definitely isn't the closest point on it

tall scroll
rigid island
#

should probably explain the usecase to get a better option / suggestion

tall scroll
#

so making a grapple system and some feedback is that with the grapple going to the crosshair you need to be precise so ideally the grapple will automatically find the nearest point of contact and auto align to that instead, hence why I can't just use a cone shaped trigger because that won't necessarily be the closest point

#

(also I gtg for like 20m)

rigid island
#

wouldnt a bigger shape like spherecast work fine here then ? it gives you more "width" to play with

visual burrow
#

hey guys, need some help with Joints - Im currently working on a mechanic for a 3d space simulator, where youre supposed to be able to chain additional ship elements to the back of your ship, kind of like a train - wagons type situation [Figure 1]

Ive set this up to work using Configurable Joints. Specifically, the player ship and every wagon has its own joint. The player ship's joint's connected body is the first wagon, the first wagon's is the second, and so on. It looks something like [Figure 2], where red is the player ship and green and blue are different wagons.

The wagons in the gif were connected manually, and the system works well enough.

However, when I try to instantiate a new wagon, and then connect it on runtime, I run into an issue: [Figure 3]

What happens is, as per the Configurable Joint documentation, if the connected body value is null, then the joint snaps to a point in world space. However, in my case the connected body is not null at that point [Figure 4], which is done as such:

I have a class JointComponent that handles joint manipulation, and it has a method Connect that is called from my WagonManager class whenever a new wagon is created:

public void Connect(GameObject connectedObject)
        {
            if (joint.connectedBody != null)
            {
                Debug.Log("Tried to connect to a joint that already has a connected object");
                
                return;
            }

            joint.connectedBody = connectedObject.GetComponent<Rigidbody>();
            
            Enable();
            UpdateAnchors();
        }

#

Where Enable just sets up the Joint values so it works (necessary to set them all to 0 so that the Joint doesn't go crazy if it doesn't have a connected body):

        private void Enable()
        {
            joint.xMotion = _dataMotionX;
            joint.yMotion = _dataMotionY;
            joint.zMotion = _dataMotionZ;
            
            ...
            
            joint.xDrive = _driveX;
            joint.yDrive = _driveY;
            joint.zDrive = _driveZ;
            joint.slerpDrive = _driveSlerp;
        }

And Update Anchors is a method that is only supposed to be run in Awake, but I tried to run it here to try and force update the Joint. The method sets up the anchor positions:

        private void UpdateAnchors()
        {
            joint.anchor = new Vector3
            {
                x = 0, 
                y = 0, 
                z = -GetAbsDistanceFromWagonCenter() - WagonManager.Instance.wagonSpawnDistance / 2
            };
            
            joint.autoConfigureConnectedAnchor = false;
            
            joint.connectedAnchor = new Vector3
            {
                x = 0, 
                y = 0, 
                z = GetAbsDistanceFromWagonCenter() + WagonManager.Instance.wagonSpawnDistance / 2
            };
        }

Connect is called after the wagon has been created:

        private void ConnectWagons(IWagon parentWagon, IWagon childWagon)
        {
            parentWagon.GetWagon().backJoint.Connect(childWagon.GetWagon().gameObject);
        }

What ends up happening is that the wagon is correctly set up as the connected body, but the ship still snaps to the world position. What's throwing me off even more is that simply "refreshing" the joint, by toggling the "auto set up connected anchor" option [Figure 5], the ship and wagon snap together and work as intended. What could be the cause of this, and how could I solve this issue?

#

oof discord compression did a number on these gifs lol

tall scroll
sharp crypt
#

i need help with my code

tall scroll
devout harness
#

I'm having some trouble configuring a nav mesh agent: my agent has very high speed and low acceleration (it's a large boulder), which gives me the desired effect of building a lot of momentum.

The problem: when my agent hits a wall, it retains the speed it had, so if it goes into a corner, it sitz there still as it slowly decelerates all the speed it's holding onto (despite visually being still). Is there a way to make it lose/transfer it's speed as though it were a rigidbody going into the wall?

Does anyone have any tips?

tall scroll
tall scroll
devout harness
tall scroll
#

well it's physics, so my assumption would be that a lower mass would let it decrease the momentum faster but idk. Could also try experimenting with drag

twilit scaffold
#

For the purposes of getting around Domain Reload (I mean, i want to turn it off) is a Singleton considered a Static method?

devout harness
#

Oh I meant like, collisions dont seem to affect the agent's velocity at all

devout harness
#

When ideally it'd lose most of its velocity when it hits the wall

tall scroll
#

for step 3 do you mean when it collided with the wall or?

twilit scaffold
#

Unity is ignoring the fact i have Domain Reload off, kind of. 2022.3.26 when i chage a SerializedField it reloads domain, even though i have that disabled for playmode. I have 4 things to populate here. this is going to end up taking too much time in the end. I have already removed things like Visual Scripting and some other packages. this still take too long.

devout harness
tall scroll
#

I'm not sure your physics are physicsing

#

that's not how momentum works irl so idk why you expect it to do that in unity

devout harness
#

Yes I agree, that's the issue I'm having- the NavMeshAgent is holding onto its velocity for some reason

tall scroll
#

ohhhh gotcha

#

what happens when the boulder hits something other than a wall?

devout harness
#

It'll push them regardless of mass- for instance it (even at 1 mass) clipped me through a wall

tall scroll
#

I mean if it hits the player what should happen, should the player die or?

devout harness
#

Oh for now I just have some debug methods printing if it hits a player, it'll run a Kill method on the player eventually

lean sail
devout harness
#

Do I need to manually set velocity changes on agents?

tall scroll
#

in which case you could always do something like onCollision(Collider collider) { rb.velocity = 0;}

devout harness
#

Ahhh gotchya, makes sense

#

Good to know- cheers guys ๐Ÿ™Œ

tall scroll
lean sail
#

If you are using navmesh agent movement, your rigidbody should be kinematic

tall scroll
lean sail
#

The velocity was already either doing nothing, or it was fighting the navmesh movement.

tall scroll
#

figures

devout harness
#

I should clarify velocity refers to the velocity field of the NavMeshAgent

tall scroll
#

in which case my code would work, but change the velocity of the agent not the rigidbody

devout harness
#

Are there any events associated with NavMeshAgents? I don't see any in the docs but I figure it wouldn't hurt to ask

lean sail
inner escarp
#

For the people here that use Tiled to create their maps (Platformer/Topdown/etc), how do you get an individual tile's custom property?

I currently have some janky setup where it's only able to get the custom property of the Layer

spiral valley
#

i dont normally use unity. i use godot. but theres this game called YARG which is open source and im trying to export it to see if i can get it to work on console. What visual studio components do i need to export it as UWP? i downloaded the right workloads but now its just really vauge and is telling me it dont have the right components.

ebon silo
#

hello, can anyone help me figure out how to add the Test Framework experimental version in package manager? I haev "enable experimental" checkbox there, but I don't see t he latest when searching for Test Framework. Does anyone know how to add any experimental package to unity? I think maybe I can do it using the "git URL", but when I tried it didn't work

rocky basalt
#

Does async/await have an equivalent of yield WaitForNextFrame? (Im being forced to use async for Meta Quest SDK)

I just want to wait for a bool condition to become true before finishing the async Task

uncut palm
#

how could i add Aim Constraint Sources with scripts? In the editor I can just drag in any object I want, but in scripts (using either SetSource or AddSource) it says it has to be a animation.constraintsource or something

im not trying to do any complicated procedural animation, just trying to rotate one object to face another- and change that object with scripts

uncut palm
#

im not having any code problems (i mean i am but you know what i mean) i just dont know what to put in general

#

this is what i imagine it would be

#

target is a game object

rocky basalt
rigid island
tawny elkBOT
uncut palm
#

used to but it stopped

#

idk why

rigid island
#

yes well you should get it working again

rocky basalt
uncut palm
#

im just tryna get this fixed first

rigid island
#

getting the proper types, parameters suggestions when you're writing is part of avoiding these issues

uncut palm
#

already enabled and apparently working as intended

#

still not underlined though

rigid island
uncut palm
#

visual studio for unity

#

it underlines spelling errors and other things

rigid island
#

thats not visual studio

#

is VSCode

#

probably why its wrongly configured

uncut palm
#

so like

rigid island
#

show

uncut palm
#

any tips for my real issue

rigid island
#

show that is underlining the current error

uncut palm
#

dont see why but

rigid island
uncut palm
#

doesnt have anything that i can read in english if you know what i mean

#

its literally

#

like i know it adds a source

#

but how does it work unity doc... tell me....

rigid island
#

have you read the source

#

ConstraintSource

uncut palm
#

same thing

rigid island
#

what

uncut palm
#

and thats it

rigid island
#

exactly

uncut palm
#

exactly what bro ๐Ÿ˜ญ

rigid island
#

create ConstraintSource

#

with those values

#

you never created a c# object before?

uncut palm
#

so how exactly do i set a constraint source for a different object

uncut palm
rigid island
#

coding is not for you if this frustrates you quickly

spring creek
#

As the sourceTransform

uncut palm
#

im not frustrated

#

but ya know

#

better help somewhere else

rigid island
#

have some milk child

#

fixing a problem involves a series of correct steps, you want to skip to "the fix"

uncut palm
rigid island
#

because thats the object type it expects..

spring creek
#

Create the ConstraintSource struct with those parameters navarone shared. Then pass in the struct

uncut palm
#

nvm figured it out

for anyone looking back (or the mods looking at the edit logs) this is why i dont like coming to the unity discord
people dodge actually helping and instead just send unity links with no explanation.... its a cruel world for people that arent already multi-million dollar game devs with the entire knowledge of the unity universe...

clever quartz
#

Hello everyone, im wondering if theres a way to create a drawn path in unity like blender has.
ideally i can get most to all points of this line and save it to create a path
(im hoping to avoid whats seen in the image with the green background, having to create a bunch of empty objects or elements to create this path)

#

(its 2d, not 3d)

rigid island
#

you can't draw points but every click it places a point and smooths out between points

clever quartz
#

uuh fancy, thank you

old nymph
#

Hi, have a nice day guys.

#

I'd like to ask is there any way to serialize an enum property? I used [field:SerializeField] but it did not work.

somber nacelle
#

that should work just fine provided it is an auto property and is not readonly

leaden ice
sly comet
#
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class ButtonOnHoverPreviewImage : MonoBehaviour
{
    private RawImage PreviewImagea;
    private RawImage PreviewImageb;
    private RawImage PreviewImagec;

    private Texture2D previewImagea;
    private Texture2D previewImageb;
    private Texture2D previewImagec;



    // Find the GameObjects with the specified names
    GameObject objectA;
    GameObject objectB;
    GameObject objectC;

    private void Awake()
    {

    }

    // Start is called before the first frame update
    private void Start()
    {

        // Load the .png file from the Resources folder
        string buttonText = GetComponentInChildren<LevelButton>()?.GetLevelNumber().ToString();
        Texture2D previewImagea = Resources.Load<Texture2D>("Materials/LevelImages/" + buttonText + "a");
        Texture2D previewImageb = Resources.Load<Texture2D>("Materials/LevelImages/" + buttonText + "b");
        Texture2D previewImagec = Resources.Load<Texture2D>("Materials/LevelImages/" + buttonText + "c");

        Debug.Log("buttontext:" + buttonText);

        // Find the GameObjects with the specified names
        objectA = GameObject.Find("LevelSelectImagePreviewImagea");
        objectB = GameObject.Find("LevelSelectImagePreviewImageb");
        objectC = GameObject.Find("LevelSelectImagePreviewImagec");

        objectA.SetActive(false);
        objectB.SetActive(false);
        objectC.SetActive(false);
#

I'm debugging on hover. The only variable that actually sets to anything is the buttonText part

#

I have gameobjects in the scene with those exact names. and they are set to active.

#

and I have images to test with at those locations

somber nacelle
#

also you should ditch find and just drag the reference to the desired objects in the inspector instead. you will be guaranteed to get the object you want that way and you won't have several searches through the entire hierarchy

sly comet
#

I would but these are instantiated objects

#

I read through the link and I haven't seen anything I'm doing wrong. I'm still looking though

somber nacelle
sly comet
#

I'm really uncertain on how to do that

somber nacelle
sly comet
#

sorry I think I've just been trying for 3 days and it's not clicking

#

I don't see how these can help me even though that's literally the point of the page

somber nacelle
#

these provide much better ways to refer to another object than just using GameObject.Find which not only relies on the gameobject's name (which is brittle), but is also slow as fuck because it searches the entire scene until it finds an object with exactly that name

#

you also won't run into issues where one object spawns something and another is searching for that spawned object before it has even been spawned

sly comet
#

yeah I get why it's bad, I just don't know how to access these with code, even looking at that page and the examples. I think it's just not connecting for me.

somber nacelle
#

have whatever is spawning them pass them to the object that needs the references to them

sly comet
#

oh

#

lmao that sounds simple brb ty

#

although

#

the .png seems super easy

#

and I have no clue why

#

I went step by step my code is same as the reference you linked

somber nacelle
#

because you didn't actually read the page i linked about how Resources.Load works

somber nacelle
sly comet
#

i read it 3x ๐Ÿ˜ฆ

#

I didn't

#

off the top of my head it said dont include extensions, its not case sensitive, the root is the resource folder

somber nacelle
#

so then what folder must the objects be in for Resources.Load to be able to find them

sly comet
#

resources

#

but it should be right its in my project

somber nacelle
sly comet
#

Assets\Materials\LevelImages

somber nacelle
#

and has it clicked yet?

sly comet
#

I mean I see what you're saying I assumed assets was the resources folder

#

because thats what the examples used

#

and I don't have a resources folder

somber nacelle
#

so make one?

sly comet
#

will do thanks

#

my last step is passing the 3 objects to the instantiator and having it pass them down to it's creations

#

which is the other part that was confusing me I'm sorry :/

#

I've been at it for a few days it's all looking the same to me now

#

I got it to work but I don't want to settle for the roudabout find way so I'm gonna keep trying the direct passdown way

somber nacelle
#

if you need help with your implementation, you'll need to show what you've tried

sly comet
#
            // Instantiate button for the level
            GameObject buttonGO = Instantiate(buttonPrefab, buttonContainer);

            LevelButton levelButton = buttonGO.GetComponent<LevelButton>();
            levelButton.SetLevelNumber(levelNumber);
    private int levelNumber;

    public void SetLevelNumber(int number)
    {
        levelNumber = number;
    }

    public int GetLevelNumber()
    {
        return levelNumber;
    }```

I did this earlier to pass an int. I think I'm going to piggyback off it somehow and do it again.
somber nacelle
#

just so you know if you change your buttonPrefab variable to be a LevelButton type instead of GameObject then Instantiate will return the reference to the LevelButton on the instantiated object instead of the GameObject so you wouldn't need the GetComponent call there

sly comet
#

I'm sure that will make sense to me when I wake up tomorrow

#

I'll be rereading all of this

#

trying hard to learn

#

100% a better way to do this but it should work

    public void SetImagePreview(GameObject previewA, GameObject previewB, GameObject previewC)
    {
        objectA = previewA;
        objectB = previewB;
        objectC = previewC;
    }

    public GameObject GetImagePreviewA()
    {
        return objectA;
    }
    public GameObject GetImagePreviewB()
    {
        return objectB;
    }
    public GameObject GetImagePreviewC()
    {
        return objectC;
    }```
chilly surge
#

You can replace them with properties with public getter but private setter.

somber nacelle
#

also consider using an array. any time you have multiple variables with the same name except for a single letter or number differentiating them, it's time to use a collection

sly comet
#

I was doing that for my buttons since i have 30 of them for 30 levels

#

I'm trying to learn but lack a formal education so shortcuts or just bad practices pervade sometimes

#

I thank you all for the help I really appreciate it!

rapid dune
#

Hi Hello, nice to meet everyone ๐Ÿ‘‹๐Ÿ˜„, i have a question, context: im creating a Web game so i have to export to WebGL format (HTML5), but how can i protect the source code, cant anyone just inspect developer tools on the site and take it? PS: ( the code is preferably hidden )

#

Thank you if you could be able to help ๐Ÿ˜Š

chilly surge
#

You cannot, even if it's not WebGL.

rapid dune
#

Oh i seeโ€ฆ

cosmic rain
#

If you're worried about people decompiling your game, well, too bad. Even AAA level studios can't do anything about it.

rapid dune
west lotus
#

Most certainly not

#

There is some htmp generated to facilitate the webgl build

chilly surge
#

It's probably WASM.

west lotus
#

You can not make a game in just html 5

chilly surge
#

But yeah, don't bother with that. Instead focus on making your game fun for the players first, then deal with people stealing your code/cheating later.

latent latch
#

encryption first, game never

rapid dune
latent latch
#

it's a joke

#

make the game then deal with your encryption methods because what is there to steal otherwise haha

rapid dune
#

Oh i seee loll

#

Well i guess i learnt today that you can literally take any game on the internet

#

Thank you very much ๐Ÿ™

dawn nebula
#

I've got sort of a strange request. Imagine I wanted to make a scroll or some type of object that "opens up".

#

I want to create "control points" which are gameobjects that handle the scaling of the sprite mask for the contents of the scroll.

#

Aka the mask stretches so its edges are always at the control point position.

#

Is there a way to have this behaviour in the editor?

#

Or is it only something I can really do in play mode.

runic linden
#

Quick question regarding architecture: I find myself using static Actions more and more to avoid using FindObjectsOfType<T> on dynamically created objects. Currently I am working on a Toady Road clone where safe zones appear each x level segments. Ofc I could tell them to look for the game manager (via singleton i.e.) and connect them this way. Telling the game manager to listen to a static event s_OnNewRespawnPoint<Vector3> is much more convenient though.

What do you think? My intuition tells me that in small projects this is no problem but will become a problem if the project is bigger. Is calling actions like s_OnNewRespawnPoint<Safepoint> with the script broadcasting a reference to itself a possibility too or is this considered bad architecture?