#archived-code-general

1 messages · Page 388 of 1

cosmic rain
#

And how are you confirming whether a task is complete and when?

errant flame
#

Its just the scene loading things for now , problem occurs in code here

cosmic rain
#

You'll need to provide some more details on the actual issue and how you're confirming it.

humble thistle
#

Would anyone have a suggestion on how to do this better?

I wanted to create "fishing pools" on the fly depending on how many json files there in a folder and that works great!
Downside is that unity cannot serialize a dict so I created a list and have each one of these pools registering it's self on it.
However, I don't feel like this is the greatest idea as I think it essentially doubles the memory used by each pool (if I am right).

Anyone else have a better idea?

https://pastebin.com/czDgUZvH

latent latch
leaden solstice
humble thistle
#

I believe I missed a bit of context, I just want to serialize it so I can view it in the unity editor it's self. I don't actually have a need to write to a fishing pool here

latent latch
#

Don't use dictionaries, use structs then initialize the dictionaires in Start()

spark stirrup
#

how hard is it to allow render textures to render through other render textures?

cosmic rain
spark stirrup
calm slate
#

Is anyone able to help me with why my agent in mlagents isn't moving? I dont think it's a problem with the AI related part of the code. I don't have any errors but it doesn't move.

cosmic rain
cosmic rain
tawny elkBOT
calm slate
cosmic rain
calm slate
#

the // convert keyboard inputs to movement and turning

#

that doesn't do anything?

#

this is source code from a tutorial on unity learn so I don't really understand why it doesn't work

cosmic rain
#

You're only querying the input. Not applying it anywhere. Not changing the position of the object or adding forces/setting velocity.

calm slate
#

they provided the actual c# file

#

anyways, I did end up fixing the problem so

cosmic rain
#

How did you fix it?

calm slate
#

used chatgpt

#

had to update to newer api too

cosmic rain
#

I mean, what did you change in your code?

calm slate
#

there's a lot there that I didn't show

#

but that section was not the problem

cosmic rain
#

Because you probably omitted the part that I was talking about.

hybrid cloud
#

Hey guys im having some strange behaviour with rendertextures.
Basically, I have 2 seperate cameras rendering to 2 seperate rendertextures
then, in a loop, for each render texture the texture data is retrieved from the gpu with AsyncGPUReadback.RequestIntoNativeArray (small note, this problem occurs regardless of the amount of cameras/rendertextures, even if just one)
then for each one it loops over all the pixels and determines which one is the brightest, and displays that so i can see it.
The weird behaviour im experiencing, is that for some reason it only factors the brightness of some things into the value/result from the gpu (some things being the sun in my scene), and for some reason the game objects that are clearly also in the texture just dont count
in the pictures you'll see the value with a blank shot, the value with my sun (the moon) in the shot, and then the value with a very bright sphere that should count towards the brightness but just doesnt
I'm not sure why the value I'm reading from the GPU isn't consistent with what's rendered to the texture.

#

i think im just gonna display what im getting on the gpu directly onto another texture just to investigate

#

so when i write that data im reading back to a texture it also shows the white sphere
i deleted the sun for good measure
and it still just doesnt factor in

#

like, its the same data

#

welpp

knotty sun
#

what is the point of your for loop, it doesn't actually do anything

hybrid cloud
#

i just figured it out

#

this is better

#

and works now

#

there was never a problem with the data

knotty sun
#

not a good way to calculate color intensity though

hybrid cloud
#

what would you suggest?

knotty sun
#

convert to HSL

covert dust
#

Alright, I need someone enlightened in the ways of rendering:

Is there a sensible way of making something render on top of everything else (3D space), regardless of Z sorting and such, that doesn't use a second camera? The project is in URP.

#

I tried solving that by copying and modifying the preset PBR shader so that it renders during the Overlay pass, but that causes some transparency issues.

#

to get a bit more specific, underlining what I added to the basic shader:

Tags{"RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "UniversalMaterialType" = "Lit" "IgnoreProjector" = "True" "ShaderModel"="4.5" "Queue" = "Overlay"}
ZTest Always

cosmic rain
#

You'll probably need to issue the rendering command with the lowest priority or modify the renderer or material priority if that's even possible currently.

covert dust
#

Still a toddler in the rendering topics so that sounds beyond me at this moment. I did not even start reading through the details of what the rendering pipelines are about.

#

But lemme check something

maiden fractal
cosmic rain
covert dust
#

wouldn't that be the Queue property? it has a value range of 0 to 5000

#

Overlay is a constant that equates to 4000

#

but any values above 2500 are treated as transparent objects

#

which changes some rules about how rendering is handled

cosmic rain
#

Yes, that.

covert dust
#

so yeah, I'm way past that step 😁

#

And the result is not very good

#

Exhibit A:
player's equipment rendering under far away decals

#

funny bit? the decal has a render priority of 2000

#

so this interaction makes literally no sense

hybrid cloud
cosmic rain
# covert dust so this interaction makes literally no sense

I'd start by looking at the frame debugger and seeing where in the queue does your object and the decal render. As well as possibly seeing if it's a depth buffer issue.

Deferred render pipeline usually renders all objects in several passes: depth - opaque - transparent. If your object doesn't render into the depth buffer, transparent objects like the decal would definitely render on top.

Btw, this kind of features(first person hands) are usually rendered by a separate camera to avoid all these issues.

maiden fractal
covert dust
#

and FSR in URP is hard limited to work with a single camera

cosmic rain
covert dust
#

the head developer of FSR3 for Unity asset

#

I mean, it still displays stuff on screen, but both looks bad and causes performance hitches

#

would be cool if I could just render both cameras to one texture and then FSR that thing, but that doesn't seem to be on the table

#

the set up only allows direct camera feed input

abstract coral
#

hi there, is there an official answer to loading large video files for VR/Android? im looking at videos >2GB because of high resolution (8k)

cosmic rain
covert dust
#

👀

#

that sounds like it might work

#

let's try

#

the project is using deffered rendering instead of forward so that's out of the question 💀

arctic steeple
#

I need a bit of help with direction for my career.
I want to be an intern level Unity game developer , what should I study/focus on, which minimum level for each skill should I reach , what should my learning path,projects be for the quickest result .
i really need an advice since my family gives me 4 months before I have to find work .

mellow sigil
#

The most important thing when looking for a job without prior experience is the portfolio, so that's what I would focus on

#

That said the chances of getting a job in 4 months are very slim no matter what you do

arctic steeple
#

I just need my levels to reach the required level

mellow sigil
#

There are no levels in real life

trim schooner
#

Get a temporary job. Learn game dev in your spare time, it will take longer than 4 months

arctic steeple
#

Then what should I focus on, what skills, knowledge should I get first ?

thin aurora
#

At the very best get a job that is fine with teaching programming

#

Learning proper programming is a big part of learning Unity so you can get experience in using C# in general or perhaps something similar

#

A lot of concepts apply in general

trim schooner
#

oh no.. I've split that up incorrectly.. you want to an intern job as a Unity Game Developer.. ignore the above

#

Make and finish at least three complete projects (project != game) for your portfolio.
Show an eagerness to learn and never stop learning.

arctic steeple
#

I think I will get there eventually, but I want to do things more efficient, I really need some help with it.

trim schooner
#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

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

arctic steeple
#

I tried Unity Learn, but they are too slow and I'm looking for a more hands-on aprroach as I like making my own projects

spare dome
#

You are supposed to follow along in the pathways by making a project with them

#

if you want a job in programming, you must know these skills to impress the people who are hiring you, There are tons of guides and tutorials on unity and C# to help you do so

#

You can only learn so much from guides and tutorials like the link above, you must apply these new things into a couple projects, If these tutorials and courses are to slow for you, You would have to just start making projects so you can learn more, as for things you do not understand use the documentation (which will most of the time clear things up).

arctic steeple
# spare dome if you want a job in programming, you must know these skills to impress the peop...

Yes, that's why Im looking for the minimum knowledge and skills required for an entry level job, and the direction to learn about them ( Such as how to use serialization, how to implement spawners or ways to refer to an object ,.... ) I only know some of which I have to learn, but my knowledge about them is very fragmented and I don't have a proper learning path for those who want to make a project. So I hope someone can help sharing a path/ document how to learn , what to do, what to make first for a more efficient and easy to understand path without having to use Unity Learn (honestly they should update that and uploads the video on youtube, it would help alot).

spare dome
#

There is always google to learn specific skills that the pathways or beginner tutorials do not teach you, you can use documentation to learn pretty much anything in the API and engine you are unfamiliar about but have the basic understanding on what it is, you can always look up intermediate courses for unity and or Csharp as well, remember the !docs and google are your friends https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/, Also to add on, you should not be looking for the minimum knowledge for a job, you should be looking to strive and learn so you can impress the people who are hiring you so they pick you over other candidates, for if you only strive to be the minimum you will learn nothing but the minimum.

tawny elkBOT
tulip spruce
#

I have recently got multiple occasions when me and a collaborator receive merge conflicts when attempting to merge a feature branch to the main branch. And It happens usually because gameobjects are deleted or re added to scenes etc. What are some good conversations or good practice to make it less troublesome?

trim schooner
#

dont allow more than one person to work in a scene at the same time

dusky lake
trim schooner
#

use multiple scenes

marble python
#

I'm encountering an issue where my particle system will play in the scene, and will activate in game mode when using play on awake, but it won't activate when I use the .Play function.

Does anyone have any suggestions?

thin aurora
#

This is a coding channel

marble python
#

I'm trying to activate it via code. What channel would be more appropriate if not this one?

dusky lake
#

i assume you have child particles, that wont trigger without the true

thin aurora
trim schooner
#

pretty sure it's .emit or something

#

maybe not

dusky lake
marble python
trim schooner
#

the bool is just for withchildren

spare dome
#

is the particle system disabled, or the object it is on?

marble python
# thin aurora Perhaps share your code in that case

Sure

public abstract class BattleMovementController : MonoBehaviour
    {
        protected Vector3 EndPoint;
        public float MoveDist { get; set; } = 1; 
        public readonly float MoveCooldown = 0.2f; // Cooldown between movements
        public readonly float MoveSpeed = .05f;
        protected float LastMoveTime;
        protected bool CanMove;
        protected Coroutine MovementHelperCoroutine;

        [SerializeField] protected ParticleSystem _moveDustTrail;
        
        protected void Start()
        {
            Instantiate(_moveDustTrail, transform, false);
        }
  }
public class PlayerControllerBattle : BattleMovementController
    {
      protected override void TryMove(Vector2 direction, float moveSpeed = .05f)
        {
            Vector3 newPosition = new Vector3(TruncateFloat(transform.position.x + (direction.x * MoveDist)),
                transform.position.y, TruncateFloat(transform.position.z + (direction.y * MoveDist)));

            //Bounds must be withing designated player area;
            if   (!BattleStateMachine.Instance.BtlGridManager.GridBoundsPlayer.Contains(newPosition)) return;
            CanMove = false;
            EndPoint = newPosition;
            if (direction.magnitude != 0)
            {
                Debug.Log("Particle system should be generated"):
                _moveDustTrail.Play(true);
            }
            MovementHelperCoroutine = StartCoroutine(BattleMoveHelper(moveSpeed));
        }
    }
trim schooner
#

pls put the cs after the three back ticks.. so it's colour coded and readable

#

!code

tawny elkBOT
trim schooner
#

copy exactly as it is in that msg ☝️

marble python
trim schooner
#

move the _moveDustTrail.Play() to some where it gets called without any conditions infront of it

marble python
#

I've tested it by moving it to the line right after it's instantiated and I still don't see anything.

trim schooner
#

This is what I had to do in my asset

ParticleSystem.EmissionModule dustEmission = _moveDustTrail.emission;
smokeEmission.enabled = _shouldEmmit;
marble python
#

Thank you for your help everyone.

trim schooner
#

😄

dense edge
#

i have been trying to remove grass from area of a instanced game object. i already lost hours on it, anyone have some idea how to grass from a radious around my gameobect in unity?

swift falcon
#

Ive been thinking about remaking my dialogue system in Unity 6, but i'm wondering if I should still use the graphview or move to something different like the new behavior package.

knotty sun
swift falcon
#

its been a nightmare to deal with for the past few months due to the lack of support

#

Frankly im willing to dive into the new one due to the fact its going to be properly supported (although i probably wont swap yet because the first release of the game will probably still be Unity 5)

rugged fulcrum
#

Not really coding related but i'm wondering if i can make a Mesh using a custom vertex layout, i want to use half2s for 2d positions, and remove normals and tangents. I assume I can set set vertex attributes somewhere, but i'm not entirely sure how

late lion
rugged fulcrum
#

generated in a script

late lion
rugged fulcrum
#

Ill look into that, thank you

safe zinc
#

Why exactly I have this as part of my build data? Does the Lit.shader is a text file or it's the compiled version of it?

late lion
winter valve
#

i have an rectTransform object with height set to canvas height but it's higher. y?

plain trail
#

why am i getting the exact same error 6 fucking times

rigid island
hexed pecan
plain trail
leaden ice
#

You need to fix it

plain trail
#

how

spare dome
#

read the error

leaden ice
#

Stop trying to access a component on the object that doesn't exist

spare dome
#

and apply what it says to your script

plain trail
#

this

#

does it say here?

spare dome
#

did you assign the animation in the inspector

plain trail
#

yes i think

leaden ice
#

You don't need to

#

You need to just not be doing that GetComponent

#

Or that component needs to actually exist

robust dome
#

is Animation componenet still a thing

spare dome
#

oh yeah my bad 😅

leaden ice
#

Yes

#

Well you would either assign it in the inspector or in the code, but not both

naive swallow
leaden ice
leaden ice
spare dome
#

that looks like the documentation code 🤔

leaden ice
#

Not an animation

rigid island
#

animation != animator

naive swallow
# plain trail

Okay what about the Animation component that you're getting in code? Show a screenshot of that one

plain trail
naive swallow
spare dome
plain trail
naive swallow
#

the words "Animator" and "Animation" are not the same word

plain trail
naive swallow
plain trail
naive swallow
#

Which is neither an Animation or an Animator. They both use the clips

naive swallow
#

There's Animators, Animations, and Animation Clips

plain trail
#

ok

#

not where are the animations

#

because you are looking for that

#

maybe

naive swallow
# plain trail

So, if you want to reference this component, you should use this component's name

plain trail
#

what component???

naive swallow
plain trail
#

and what am i looking for

naive swallow
#

Is that the component you want to reference

plain trail
#

yes

naive swallow
#

Then you would use that component's name for the thing you want to GetComponent

#

Instead of the name of a component that you do not have and are not trying to reference

plain trail
#

like this?

naive swallow
plain trail
#

yes

#

also i just realized how terribly i misspelled pineapple

naive swallow
#

Okay let's go with that. Show it

rigid island
#

should probably configure ide. How is there a whitespace in a class

plain trail
#

are you talking about this

trim schooner
#

that is not a component

naive swallow
#

GetComponent gets components

#

Not asset files

plain trail
#

ok wait

#

all im trying to do is use code to change animations

spare dome
#

anyway you should not be using the animation component as it is old and legacy, instead you should use the animator which is newer and recommended

naive swallow
naive swallow
#

So, get the component you actually want to reference

#

and change the animation state from there

rigid island
leaden ice
tawny elkBOT
#

:teacher: Unity Learn ↗

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

dense edge
#

for some reason

rugged fulcrum
#

ahh yess 对文档有任何疑问,请移步至开发者社区提问,我们将尽快为您解答

rugged fulcrum
#

what is this supposed to say though?

#

nvm im prob missing a font

rigid island
rugged fulcrum
#

weird

#

page works fine in chrome but im missing a font in firefox

rigid island
#

i use ff. maybe try reinstal

tulip spruce
#

well I have two, one for the menu

tulip spruce
trim schooner
crimson musk
#

Hi, this is my first time writing here but I just don't know what to do atp.

I'm making a game for a college project. It generates a map out of a pool of prefabs. Each instantiated prefab has a DungeonEntrance that has a special material that will change color depending on the difficulty. For this I have three scripts IntersectionManager (generates the map), DungeonEntrancePreset (a scriptable object that holds a color, and a difficulty), and DungeonEntrance (generates a difficulty, and based on it, takes the correct preset and loads it to the material). All of this works fine, but I want to take the difficulty generation from DungeonEntrance to IntersectionManager, and it just won't load the preset for some reason.

1st image is the block of code in IntesrsectionManager that generates and assigns the difficulty to the street. Second and third is the DungeonEntrance code. Fourth is the DungeonEntrancePreset Scriptable Object.

please help

#

sorry, I f'd up with the images. Here's the one that is the block of code in IntesrsectionManager that generates and assigns the difficulty to the street.

civic nymph
#

I have a Scriptable Object that holds a prefab in an object pool.
I have a second S.O. that holds prefabs to clone and spawn.
I want this S.O. spawner to use the prefabs in the pool, rather than cloning them.
What is the best way to do this without nesting an S.O. inside of the another S.O.?

winter valve
#

my text field looks like this. on first editing it all erases but after this it doesn't & i don't see the cursor. there's some code for this - the most that may interest - in update() i edit textfield & stopping doing it until in-game writing stops. i know, it's selecting, it doesn't seem to edit in game but it edit's in the editor window

leaden ice
tawny elkBOT
crimson musk
#

sorry ): as I said first time here

leaden ice
# civic nymph I have a Scriptable Object that holds a prefab in an object pool. I have a seco...

I have a Scriptable Object that holds a prefab in an object pool.
What do you mean by this? The SO references an ObjectPool? And the contents of the pool are... prefabs? Or do you mean instances of prefabs?

I want this S.O. spawner to use the prefabs in the pool, rather than cloning them.
The second SO or the first one? And I assume you mean instances, not prefabs. But yeah that's kinda the whole idea of an object pool.

What is the best way to do this without nesting an S.O. inside of the another S.O.?
What do you mean by nesting exactly? You mean just referencing one from the other?

finite urchin
#

I want to attach scripts to projectiles at runtime, but im not sure how to get the script i attach at runtime to interact with the projectile its attached to. specifically, i am going to spawn in the projectile which will have a hitbox component, and after the projectile has been spawned in, attach a script to it (ill call it script X) and then when the projectile hits something, script X will run its code.

leaden ice
#

when the projectile hits something, script X will run its code.
This is usually done via physics callbacks e.g. OnCollisionEnter

crimson musk
# leaden ice !code - and it's also unclear what your actual question is.

So, I have a isometric game with a that has a semi-procedural generated map, to generate the map, I have prefabs that are instantiated dynamically depending on the exits (like The Binding of Isaac does). Each of these prefabs (which are tilemaps) have nested a DungeonEntrance tilemap, which has a shader material and a script called DungeonEntrance (the one on the photos). And as child of that DungeonEntrance tilemap, there is a collider that has attached another tilemap with a tilemap collider and a composite collider, as well as an IEntractable trigger script whith OnEnter, OnInteract, and OnExit. So the idea is that at runtime, each street gets assigned a difficulty when they are instantiated, then the player walks on the collider, calls OnEnter (which has assigned in the inspector the TurnOnDungeonColor method on Dungeon Entrance) and changes the color of the material of the DungeonEntrance depending on the difficulty assigned (which is generated on the script of the last picture). These colors are decided by some scriptable objects presets I made (3rd image).

The problem is that everything works fine, until I walk in the collider and the debug.logerror that is in TurnOnDungeonColor method is displayed. But I don't know why is the _current preset null. Everything is correctly assigned on the inspector, I debugged all processes and none of them give errors.

I really hope this was more understandable.

finite urchin
# leaden ice What's wrong with the usual ways (i.e. GetComponent etc)? But also - why attach ...

sorry if that seemed like a newby question, im relatively new to unity. based on what i just read on getcomponent, if i attach a script X to my projectile, and when my projectile hits something, i can just call getcomponent<script X> and then call any methods in script X from the getcomponent call to apply to whatever I just hit (i.e. inside the onCollisionEnter method)?

also you might be right in that I don't necessarily need to attach it at runtime since for some reason I thought that objects could only have one script on at a time. I can just attach script X to it beforehand.

on prefabs, I will have to look into them to see if that is somethign that could be useful for my case.

leaden ice
leaden ice
# finite urchin sorry if that seemed like a newby question, im relatively new to unity. based on...

if i attach a script X to my projectile, and when my projectile hits something, i can just call getcomponent<script X> and then call any methods in script X from the getcomponent call to apply to whatever I just hit (i.e. inside the onCollisionEnter method)?
You call GetComponent on a GameObject or any component on that GameObject to get a component from that object.
You can also just call it directly in a MonoBehaviour and it will get a component from the same GameObject that script is attached to,

#

But yeah these questions are the bare basics of UInity, really you should be in #💻┃code-beginner if you're a beginner

finite urchin
#

yes i was thinking that after reading my response so i will move my questions to that channel

leaden ice
#

YOu can work backwards to find out

crimson musk
#

the debuglog.error is on the second image nearly at the end.

And that's the thing, I really don't know how to figure out what's failing.

I want to add that, I used to have the GetRandomDifficulty method on the DungeonEntrance script instead that of the IntersectionManager, and this way it worked just fine, and it's the exact same logic.

spare dome
cosmic rain
leaden ice
#

more logs and/or attaching the debugger

spare dome
finite urchin
#

they arent going to be bullets but rather spells that the player casts but yeah i guess the sentiment would still be the same. I am doing some more research into prefabs and the getcomponent and am probably not going to add the script onto the projectile at runtime and instead add it once when the spell is created by the player in the craft menu

crimson musk
#

I debugged the processes can I share the screenshot?

meager marlin
#

I really need a hand here, but my problem involves some extensive coding. At one point the game was working, and when I tried to change something in my existing codes, the whole sprites and cards aspect of the game stopped working (I'm doing something akin to Reigns). I'm just wondering if I should post the entire thing here with links to break down the code, or not. Mainly because of it being an extensive problem, looking at three different codes.

oblique spoke
oblique spoke
tawny elkBOT
crimson musk
meager marlin
crimson musk
#

Debug on awake? yes, I just did, also initialized

cosmic rain
#

When you expect it to not be null

#

Also, you still didn't share the code correctly, so I can't even confirm what we're debugging.

oblique spoke
spare dome
#

the easiest way to fix code that was originally working but is now broken is to back track and see what you changed that broke everything and find a way to fix it whilst getting the outcome you desire

crimson musk
#

Also, I didn't put the whole IntersectionManager code because the only part of that code handling the difficulties is in that method, but I can put it there if neccessary.

meager marlin
oblique spoke
meager marlin
oblique spoke
meager marlin
#

So essentially, I wanted to make tweaks to my scripts to make an event system, in which some cards that showed up to the player had orbs atop them, with flames indicating the "number" of the event the player was in (Ranging from one to four). In the midst of that, the script would make a choice of swiping the card left or right, trigger the next event depending on the choice taken, causing the card to be "turned off" and not appear in the deck anymore, and make the next number of the event pop up instead.
But when trying to change the code accordingly, the sprites of the cards I've made became messed up, and the whole card system just went bollocks and refused to work anymore. Even further than that, replacing the code with the old one to attempt and mend the situation, didn't fix it at all, and the card system was still fucked up. Needless to say, I am TOTALLY lost as to what to do here.

These are the Card, CardDisplay, and GameManager scripts BEFORE I've done any changes.

And these are the Card, CardDisplay, and GameManager scripts AFTER the changes.

(All the links are safe, I just did it this way to make the chat less cluttered.)

cosmic rain
# crimson musk https://paste.ofcode.org/iRyN2ehN3NMyd64NrRnRCd I put everything in a single pas...

There are several possible explanations:

  1. The object that the method is called on is not active, so awake or start were never called on it, thus, even if the preset is null, there wouldn't be a log about that.
  2. The method is called on a destroyed object that doesn't have valid values. This one is unlikely.
  3. The method is called on a prefab, in which case it's the same as 1.

Debugging the object that the preset is null would be the next step.

dense estuary
#

I am experiencing an issue with my radar script, the if statement inside the for loop seems to be going off twice, even though its only supposed to go off when the difference is under a certain value. https://hastebin.com/share/cabacuvequ.csharp https://streamable.com/11b59i

Watch "2024-11-22 21-41-02" on Streamable.

▶ Play video
dense estuary
#

I'm not sure what is causing this issue, as I believe the way I am calculating the angles is correct, but I could be wrong.

narrow folio
#

Anyone here has a good C# FSM library recommendation?
I'm looking at State Machine Compiler but it has its own domain language which is kind of annoying

untold shoal
#

how do i get dictionaries to appear in the editor?

vestal arch
#

or, well, you'd have to do it yourself

#

or maybe someone's already done it for you

#

but you can't do it through built-in means

untold shoal
#

oh

#

is there something like dictionaries that do appear in the editor?

vestal arch
#

and then process that into a dictionary on startup

untold shoal
#

I saw some people using the SerializedDictionary type

#

but i cant use it for some reason

#

ive seen it in vids

vestal arch
#

have you tried googling it

#

it's not builtin

untold shoal
#

okay i found some assets on the asset store

#

but all of them are broken

#

im using unity 6

pastel apex
#

Whats the best way to code enemies? I know you can have basic movement script and then a different script for each individual movesets but if you have multiple instances of that enemy then whats best way so they dont override eachother?

vestal arch
#

there is no "best"

#

and an answer of what's a good way to do so will heavily depend on how you design the enemies and what kind of game you're making

pastel apex
#

Well I have a roguelike that has 4 different enemies atm 1 ranged, 3 melee with different movesets. Havent really progressed much since dont know how I should code it. Esp if there is multiple of them in one room and where they dont mess with each other

soft shard
# pastel apex Well I have a roguelike that has 4 different enemies atm 1 ranged, 3 melee with ...

AI is kind of a big topic on its own as one enemy can have many techniques and algorithms used with it that are common in AI behaviour - for example if you want your AI to move around objects and avoid bumping into eachother you can look at "obstacle avoidance" or "flocking" AI algorithms, or you can try A* pathfinding or Unitys built-in NavMesh (which AFAIK is best for 3D and requires baking your map to identify what is "walkable" for your "agents") - if your AI only need to perform 1 set of logic at a time, you could look into a FSM (Finite State Machine), if they have complex cooperation logic, then maybe a Behaviour Tree, if they have other complex logic, maybe a GOAP system, theres lots and lots of ways to approach AI, and maybe you might need some parts or an entire implementation of a particular approach to AI - I would maybe start with looking into the different approaches with a search like "ai patterns in game development" or "ai patterns in unity", then try to plan out how your specific AI should work with the logic of one of those patterns

elder kettle
#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

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

ocean summit
#

Guys i have seen recently some issues with UnityAds that works on editor but it doesnt work on build. Im having the same problem and I tried to solve with many changes but nothing. Im using the same code of the documentation

rigid island
civic nymph
# leaden ice > I have a Scriptable Object that holds a prefab in an object pool. What do you...

The first SO references a pool in which the contents are a prefab, yeah
The second SO has a reference to a prefab which it then clones. I'm looking to have it use the first SO as a way to recycle assets.
I don't want to put one data container inside another, if possible. I'd like for the second SO to get the data from the first SO with a different method, but I don't know that that would be.

leaden ice
#

I think you're probably just confused about how references work

civic nymph
#

The objectPool SO would be placed inside of a field in the objectSpawner SO

#

the objectSpawner SO is then placed inside a third object to run it

#

I don't think I should be storing data like that

#

I'm thinking I could combine the two SOs

#

I'll look into that first

nimble eagle
#

Hello! I'm working on a 3D top down game and I'm stuck at implementing the melee attack functionality. What I essentially want is the player to stop moving on attack, turn to look at the mouse cursor in world space and trigger an overlap capsule check. The Activate method is called by the ability holder who is controlled by the player controller that uses the new input system (mouse left click).

The functionality I want: The player walks using WASD and rotates in the direction of movement but when attacking it will stop and turn to face the mouse position and damage whatever hits the capsule check. This is basically the control scheme of Hades if it helps you understand better.

Issue: Most of the times when I left click the player will rotate towards the mouse but will quickly snap back to the previous rotation. The attack direction is correctly calculated (I'm using a debug capsule function) but the player for some reason snaps back like the rotation never happened. I even disabled all of the scripts in case anything was interfering (including movement script).

The melee attack ability code: https://pastebin.com/BZ85378g

leaden ice
#

if you mean:

class ObjectSpawnerSO : ScriptableObject {
   public ObjectPoolSO pool;
}```
Then it is not "stored inside" or "nested".

It just means the spawner has a _reference_ to the obejct pool.
#

That's all

static ore
civic nymph
#

I overestimated it

knotty sun
#

you haven't even said what the issue is yet, also move to #📱┃mobile

amber musk
#

Okay

prime perch
dense estuary
# static ore May I know what you're trying to achieve with the if code block?

I have two angles, one is the angle of the ray that's on the radar screen. The other angle is the angle formed between the Vector3.forward direction, and the direction the object is from the player. I am subtracting those two angles from eachother, saying that if the difference is less than a certain number, ping an icon onto the radar screen.

hasty dove
#

Hey I have an issue that I have been trying to fix for the last 4 hours and I am stressed and getting nowhere with it...

I have My player controls with an action called submit which is assigned key values to space and enter.

There is a lot going on but it is supposed to log some information when pressing these actions within a 2DCollider. I have added debug messages and it seems that the inputs are not being registered for whatever reason.

I dont want to spam this channel with a bunch of out of context code but I would really love some help on this as its been multiple hours and i am getting nowhere

knotty sun
hasty dove
knotty sun
#

try logging before the if, (Debugging 101)

hasty dove
#

This code here should output the bottom 3 lines in the console when the submit action is pressed. this isnt happening and no amount of debugging is detecting the Submit key is being pressed/Registered

private void SubmitPressed()
    {
        Debug.Log("SubmitPressed called");

        if (!playerIsNear)
        {
            Debug.Log("Player is not near");
            return;
        }

        Debug.Log("Starting quest: " + questId);
        GameEventsManager.instance.questEvents.StartQuest(questId);
        GameEventsManager.instance.questEvents.AdvanceQuest(questId);
        GameEventsManager.instance.questEvents.FinishQuest(questId);
    }
knotty sun
#

then your action is set up incorrectly or it is not enabled or you have not subscribed the method to it

hasty dove
#

Thats what i thought at first but I cant see whats wrong with it

#

is there a way i can show you or find out myself whats wrong with it because every other action works in my input action asset

knotty sun
#

Start adding more debug .logs

twilit rune
#

how do i reference objects from two different scenes playing at the same time to a singleton in DontDestroyOnLoad?

#

and how would i make these objects interact with it/use the references?

rigid island
twilit rune
#

nope, every object just refuses to take the references due to the reference not existing, no matter what i try to set it to

#

for now, my latest try has a script that has an inspector reference to everything it needs in both scenes, instantiate the singleton in dontDestroyOnLoad, then pass those references to it, all in negative execution order

#

instantiating is the lowest order, then reference giving right after, then every other script

#

any ideas what could be wrong?

static ore
static ore
#

So what you're trying to achieve is that the object only gets pinged once per radar sweep? @dense estuary

dense estuary
#

The reason rayAngle uses -radar.transform.forward as the axis is because the radar is UI, rendered to a render texture, and displayed on an object.

static ore
# dense estuary Yes

Ah I understand now. So what you could do is to track if object has been pinged, then skip the object you've already pinged during the sweep, then clear the tracked object after the full sweep.

dense estuary
#

Hmm, that should work. One thing I've realized is that this script has gotten quite complicated, I'll probably rewrite it using rotating raycasts instead of a bunch of vector calculations.

#

However, I'm not sure how I can rotate a ray.

#

Oh, it seems you just multiply its direction by a quaternion.

turbid river
#

yeah, and then just make it visible as long as theres contact?

rugged fulcrum
#

Hi, what is the JobLength field used for when using Burst jobs? Is it just an indicator of complexity?

rigid island
#

its how many iterations it will run

twilit rune
rigid island
rugged fulcrum
#

I'm follwing catlikecoding's tutorial on procedural meshes, and i mean the first parameter in ScheduleParallel job.ScheduleParallel(job.generator.JobLength, 1, dependency);

twilit rune
#

one script instantiates the singleton and send it to DontDestroyOnLoad on awake, then i have a script on each scene with a setup like this:

[SerializeField] GameObject terrain
[SerializeField] GameObject player;

private void Awake()
{
MasterSingleton.Instance.KeycardsHUD.Terreno = terrain;
MasterSingleton.Instance.Player = player;
MasterSingleton.Instance.PlayerHealthHUD.HealthScript = player.GetComponent<PlayerHealth>();
}

to tell the Singleton its references, after that then every other script runs and tries to use the singleton

rugged fulcrum
#

Ah so it foes more than just spawn a oncurrent thread to run the task on, ty

twilit rune
#

their default execution order is set to -5 and -3 respectively, and every other script is 0 or higher

rigid island
rigid island
twilit rune
#

every scripts returns a object not set to instance of an object while trying to access it

#

it seems changing it to Start has at least reduced the amount of errors

#

hold on, i think i forgot a few

rigid island
#

okay so , which ones are throwing nre now ?

twilit rune
#

nope, nevermind

#

the amount of errors reduced were due to the references being set at the start of awake, when it had a problem, everything else after awake would simply not happen and cause other problems

#

the problem is inherently the exact same

#

i just dont understand what is possibly wrong about all this

#

everywhere else says this should work fine, script makes singleton in DontDestroyOnLoad, scripts with references send them to Instance, then every other script just takes it from Instance if needed

#

or, the scripts themselves game themselves as the reference if it needed it

#

it should work, it MUST work, but it just doesnt

rigid island
#

+screenshot errors

twilit rune
#

the reference-giving scripts are about the same as the one i've said prior

#

the errors are all NullReferenceObjections, in Awake, Start, Update, doesnt matter, if it tries to get anything from Instance, its null

rigid island
twilit rune
#

a script in each scene with default execution order -3, with private serializefields of every reference needed of that scene which is assigned to the singleton like this:

private void Start()
{
    MasterSingleton.Instance.CartoesHUD.Terreno = terrain;
    MasterSingleton.Instance.Player = player;
    MasterSingleton.Instance.VidaJogadorHUD.VidaScript = player.GetComponent<VidaJogador>();
}
#

i would show a pic, but there's a bunch of unrelated stuff there

#

the start script is just that though

rigid island
twilit rune
#

if i did i wouldnt be posting it here

rigid island
#

consequences of bad design and messing with execution order generally makes it worse
-4 means it runs before -3
Accessing Player in -4 before its assigned from -3

twilit rune
#

i dont see the problem? i create the script first (-5), i load it and check if there is another singleton (-4), and then i assign the references (-3)

#

everything else is in 0 or higher

rigid island
#

Instance.Player in that log would for example throw null because you don't assign Player until AFTER you run that line

#

so far thats the only null reference I can see since thats all you shared

twilit rune
#

oh right, the debug.log, that is just a test a did earlier and i forgot to remove

rigid island
#

I mean..this is why i requested the most recent null logs and their line number + associated script

twilit rune
#

its a singleton, if i had to share every object that tries to get a reference we'd be here for a while

rigid island
#

otherwise not sure how anyone can help here

twilit rune
#

i'll show the error log tho

rigid island
#

can give you general help ig, just ensuring the correct order since it seems thats not the case here

twilit rune
#

wait, now that you pointed it out

rigid island
#

mess with the order of execution on specific scripts if its absolutely necessary (maybe a bootsrapper object)

twilit rune
#

that debug.log only happens after every other object's Awake

swift falcon
#

can someone help me with a problem with my level system?

twilit rune
#

i gotta delay everything until after the singleton is awoke, seems like more scene shenanigans

tawny elkBOT
chilly surge
#

Who doesn't love magic numbers in script execution order

#

Only a matter of time until we get to 9999 (IMPORTANT: don't change this, this has to run last!!!)

dense estuary
#

In the start method I am trying to add one key for every icon. But it seems to be throwing an error when I try to add.

#

wait, I think I fixed it

twilit rune
#

alright, i ditched the singleton instantiator and just put it directly in the scene that will stay for most if not all of the game (its still being put on DDOL tho), now it is without a shadow of a doubt the first one to run and FINALLY be loaded before the other scripts try to set its references

fiery saddle
#

Anyone have idea why my test returns color that has 2 in red, 1.3 in blue??

twilit rune
#

every error is gone now

fiery saddle
#

cant show code really because its test for a tool which handles tweening in background but
it adds color

new Color(1, 0, 1, 1)

to the color

new Color(1, 0.2, 0.3)
leaden ice
fiery saddle
#

well why it can go over 1?

leaden ice
#

1+1 = 2

#

HDR colors

quartz folio
#

Because numbers can go over 1?

leaden ice
#

But also because it's just a number

fiery saddle
#

really thought colors are clamped in background

leaden ice
#

Nope

#

It's basically just a Vector4

latent latch
#

So I'm using Unity's character controller package and unfortunately the slope logic on it is arse, so I'm trying to resolve the issue of having a bumpy downward slope velocity.

_controller.Move(inputDirection.normalized * (_speed * Time.deltaTime) + new Vector3(0.0f, _verticalVelocity, 0.0f) * Time.deltaTime);

This is the typical movement call and I'm trying to figure out how to go about blending the input direction to that of the slope direction that's given from doing a cross product from below the player.

#

Rather, I'm not entirely sure the best way to go about it. Is the idea to just really force the velocity of that onto the slope?

dense estuary
# static ore Ah I understand now. So what you could do is to track if object has been pinged,...

Alright so, I implemented a dictionary to accomplish this, but it didn't seem to help much. I could be doing something wrong. It's supposed to set the bool in the dictionary to true after pinging once, preventing it from pinging again. But for some reason it doesn't seem to change it to true until after it pings twice? https://hastebin.com/share/acezabajug.csharp https://streamable.com/h2nzm3

Watch "2024-11-23 20-07-36" on Streamable.

▶ Play video
latent latch
#

Actually, I think what I may be having trouble with is that the Character Controller already does some sloping logic, and I think that's actually creating problems

rigid island
# latent latch Rather, I'm not entirely sure the best way to go about it. Is the idea to just r...

not sure how it will work for you but here is how I do it . just realized naming was pretty bad when I made it, should've called the method AdjustForSlopes or something 😅

 private Vector3 Move(Vector3 velocity)
    {
        if(Physics.Raycast(transform.position, Vector3.down, out var hitInfo, 1.5f, groundedLayers))
        {
            var slopeRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
            var adjustVel = slopeRotation * velocity;

            if(adjustVel.y < 0)
            {
                return adjustVel;
            }
        }

        return velocity;
    }```
#

cc.Move((moveInput.y * currentMovementSpeed * Time.deltaTime) * Move(transform.forward) +( playerVelocity * Time.deltaTime));

latent latch
#

I'll play around with that ty

dense estuary
static ore
#

@dense estuary I haven't looked at the new codes you posted. But going through the first code you posted here, https://hastebin.com/share/cabacuvequ.csharp

I assume the calculations are correct here?

#

There are several ways you could do that. Since you're going with the dictionary way. (Still using your first code posted)

Add this in your radar class:
`private Dictionary<GameObject, bool> pingedObjects = new Dictionary<GameObject, bool>();

private float lastResetAngle = 0f;`

And in RadarFunctionality(),

`if (rayAngle < lastResetAngle)
{
pingedObjects.Clear();
}

lastResetAngle = rayAngle;`

^ You could either clear the dictionary or reset all values to false, I'll leave that to you

In the for code block add:

`GameObject detectedObject = results[i].gameObject;

bool hasBeenPinged = false;

if (!pingedObjects.TryGetValue(detectedObject, out hasBeenPinged) || !hasBeenPinged)
{ // the rest of the codes`

*On edit:

Also don't forget to update the ping status or whatever you want to call it to true in the if block.

dense estuary
#

I feel so dumb but now it makes so much sense

#

While I was using the timer to fade out the icon, the coroutine couldnt change the rayAngle variable. So by putting the fadeOut into another coroutine instead, it prevents the rayAngle variable from getting stuck.

static ore
#

Ah

dense estuary
#

So, the dictionary system is working now aswell.

#

incase the detection range is too large, it will still only ping once

static ore
#

Glad you figured it out. Even I've learned something 😅

static ore
fiery rover
#

Anyone know if their is a way to grab all player prefs keys? i guess somthing like this even though it does not exsist string[] allKeys = PlayerPrefs.keys;

rigid island
#

better off inplementing your own system and using json

fiery rover
#

dang alright

vapid apex
#

when i have a class Item item; and inside Item i have a reference to a ScriptableObject called ItemData itemData
is there an easy way to save item to json and when loading again it automatically links to ItemData again?
like, maybe json storing the asset path of the ScriptableObject or so?
or do i need to create a lookup table or so?

#

binary instead of json would also be fine

#

maybe i could make them Addressables and store the path?

twilit rune
#

why is a script's awake function executing before another script's start even though the the start script has a lower default execution order?

vapid apex
#

it doesn't

#

Awake comes before Start

twilit rune
#

they are on two separate scenes that are running at once

#

but it shouldnt matter? unless it runs one scene first before moving to the next

vapid apex
#

if you want a chain of functions where execution orders matter, then have a public static event on the script that shall execute first, and then invoke the event and the others do something when the event is called

twilit rune
#

what about OnEnable? seems like its happening before my singleton's awake

#

also on order -5 while the enable is 0

humble thistle
#

Are you unable to add to a list of a struct inside another struct?
I can't really seem to find a solid answer on google but I am unable to add this struct to the items list

hexed pecan
#

Is this even unity tho

humble thistle
humble thistle
frail dust
#

I am wanting to move items inside a list, so i need a for loop for it. Now I am using it inside a while (elapsedTime < 1f), which is inside a coroutine as well. Am I doing it right or is there a better way of doing it?

hexed pecan
#

It's unclear to me what you want to do, can you elaborate?

frail dust
#

The coroutine is responsible for moving the pieces, updating their target positions

#

while loop is for making it move within a fraction of time

#

and for loop to iterate in the list

hexed pecan
#

Yeah a for and while should do it

frail dust
#

I am making a match 4 based game

hexed pecan
#

As long as you yield inside the while

frail dust
#

in which if u swipe, all that elements in row or column must shift by 1 posiition

frail dust
#

i did a yield return null

hexed pecan
#

Yeah this sounds fine

frail dust
frail dust
# frail dust For reference: https://pastecode.io/s/0c6sb7tu

In this, i made the last element to move to 1st element's position, since they are on opposite screens, i manually made them wrap around the opposite screen by first making it move to end of bounds, then changing the target position.

For the middle elements (except the last element) i made a list of target positions and im planning for loop so they move and shift to other element's position and rotational alignment

outer otter
#

weird interaction with this 1/10 placement issue... any ideas? taken from codemonkey

sinful marsh
#

uhhhhh in the ui anybody know how to tile an image in one axis and is stretched in another?

cause wrap mode per axis seems to be not working

dusk apex
# humble thistle Are you unable to add to a list of a struct inside another struct? I can't real...

Primitive arrays aren't dynamic sizing so you cannot add an element to it.cs int[] data = ...; data.Add(...);//Error!The warning implies that it (the primitive array), referenced as a list interface (who knows why.. maybe implicit casting etc) could not access it's underlying implementation of Add - because it (implicit cast to the Array class type) doesn't actually implement one.

tldr: That isn't an items list. That's an items array. Use List<WeightedItem> instead.

night comet
#

was creating a pause menu until i discovered this bug where the player jumps even while in the pause menu and turns it off. It does not happen when i pause and unpause the game using the escape keybind which i made. When you first press the resume button, it triggers there and is a hassle. Anyone know what went wrong there?

outer otter
#

!code

tawny elkBOT
night comet
#

my bad

outer otter
#

ur gud just helps with readability

#

from my opinion it looks like your bool is kind of flopped. if i follow the update code, if paused is true, then execute Pause(), which sets paused to true

#

same with the Resume function. I could be wrong, but try switching those first

night comet
#

actually...

night comet
#

it's just assigning it again, it may look wrong but it doesnt make a difference

outer otter
#

okay, jus makin sure, usually anything written over is gonna be in update, rather than a method being called once in this case.

#

you can test it out thats the only surefire method, other than that im not too sure

night comet
#

oh wait so instead of it having to check for it evvery single frams, i could just make it check the instance i call that method

#

isnt that right

outer otter
#

ehh not what i was gettin at, instead of the places you put ```cspublic void Pause()
{
pauseScreen.SetActive(true);
Time.timeScale = 0;
paused = true;
}
public void Resume()
{
pauseScreen.SetActive(false);
Time.timeScale = 1;
paused = false;
}

instead put 
``` cs
public void Pause()
{   
    pauseScreen.SetActive(true);
    Time.timeScale = 0;
    paused = false;
}
public void Resume()
{   
    pauseScreen.SetActive(false);
    Time.timeScale = 1;
    paused = true;
}
#

try this and see if theres a better outcome. the more i read it the more it doesnt make sense though

#

i feel like your bool 'paused' should be set to true in order to enable the use of the Pause() class, instead of calling it inside the class. it seems repetitive

#

currently when you check if 'paused' is true, you still set that 'paused' variable to true, so it doesnt make sense to have it there. same with the other class. @night comet

night comet
outer otter
#

looks like it aint got no gas in it

#

lol, yea that didnt work, after i reread my edit i thought it wouldnt work facepalm

night comet
#

😭

#

i jus turned it into a feature

outer otter
#

sweett lol onward young lad

night comet
#

hehe

outer otter
#

lemme look further

night comet
#

thanks for the help tho, i kinda know how to fix it now but idk if im wise enough to do it 😭

outer otter
#

lol id take out the paused set code, it seems arbitrary if i use that word correctly.

#

idk how to help tho, i have to watch you bleed out hehe

frail dust
#

Hi Folks, I am making a match 4 based game in which if If we swipe in a direction, all the elements of that row or column will shift to the next position. And the last element will wrapped to other side of screen and move to 1st item's position.

But I am facing an issue, I have a coroutine in which I have 2 while loops. The 1st while loop is responsbile for moving the last item to the end of bounds.min or bounds.max depending upon swipe direction, it also has a for loop which iterates over the other items and shifts them.

The 2nd while loop is responsible for moving the last item to 1st item's position as it changes the target position.

Problem: Earlier I didnt have this for loop so My last element was properly moving and shifting to the 1st item's position. But now with the for loop, other items are shifting correctly but the last element doesnt reach the 1st item's position, it stops just before it

Code: https://pastecode.io/s/cf3b18h8
(Refer 69th line)

kind willow
#

So I want to remove some elements from a list in a loop
Should I rather create a second list where I assing what am I going to remove in the end
or iterate backwards removing elements?

knotty sun
#

iterate backwards

indigo frost
#

So im having the same issue as the guy in this Topic, and i still haven't found a solution, im trying to use UnityEngine.InputSystem in an External Assembly but when i try to get the Scroll wheel (which is a Vector2), I get an error: "error CS0012: The type 'Vector2' is defined in an assembly that is not referenced. You must add a reference to assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.", and when i add a CoreModule Reference it just wont build.

knotty sun
#

And why wont it build?

indigo frost
#

Hold on

indigo frost
# knotty sun And why wont it build?

error CS0433: The type 'Vector2' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
error CS0234: The type or namespace name 'CoreModule' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?)
error CS0433: The type 'MonoBehaviour' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
error CS0433: The type 'GameObject' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
error CS0433: The type 'Rect' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'

knotty sun
indigo frost
#

alr

knotty sun
# indigo frost https://hatebin.com/ydzybmnrsm

so you are using the .dlls from the wrong place. You need something like this

    <Reference Include="UnityEngine">
      <HintPath>C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Managed\UnityEngine\UnityEngine.dll</HintPath>
      <Private>False</Private>
    </Reference>
    <Reference Include="UnityEngine.AnimationModule">
      <HintPath>C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Managed\UnityEngine\UnityEngine.AnimationModule.dll</HintPath>
      <Private>False</Private>
    </Reference>
    <Reference Include="UnityEngine.CoreModule">
      <HintPath>C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Managed\UnityEngine\UnityEngine.CoreModule.dll</HintPath>
      <Private>False</Private>
    </Reference>
indigo frost
#

Sure, ill try it

#

But the dlls work and i just copied them from my unity 6 install to the Libs folder

knotty sun
indigo frost
#

There are? I only found one UnityEngine.CoreModule, but sure ill look again

knotty sun
#

multiple UnityEngine which is what is giving you the problem

indigo frost
#

Ohh

#

Alright the new Core is 0.7 mb more than the other one

#

Oh yeah tysm man!

upper pilot
#

Whats a reasonable way to calculate Vector2 out of Vector3?
Currently a character is moving on X and Z axis(Y axis is for jumping)
But when converting to Vector2 X/Y are used, is there a way to swap it somehow?

#

Since a character moves ona flat terrain I'd like to use x/y for movement, even input system uses x/y when asked for Vector2, we are converting it:

            Vector3 movement = new Vector3(MovementInput.x, 0f, MovementInput.y).normalized;

But I want to calculate the direction from enemy and the player, do I have to manually convert it from Vector3 to Vector2 in order to do that?

fiery saddle
#

Not sure where to put this question but

  • I edit the prefab
  • CTRL + S
  • Run the game and it works
  • Open prefab, and changes are not there
  • Run the game again and it doesnt work

How is that possible?

upper pilot
crude mortar
#

then do

var myVec = new Vector3(bla bla bla);
var vec2 = myVec.XZ(); // Convert to Vector2
var vec3 = vec2.X0Y(); // Convert to Vector3
upper pilot
#

Thanks, I will give it a go 😄

upper pilot
crude mortar
#

I usually make a file per extension class but it is not a rule

upper pilot
#

when I make a new class in VS2022 it asks for a class name/file name so I always assumed its expecting 1 class per file(even tho I tend to have multiple if those are smaller classes/structs that are used within the main class)

#

That sounds reasonable, who knows I might have more extensions in the future 😄

knotty sun
upper pilot
#

Unity if its a monobehaviour right?

#

but I can have a monobehavior + regular class I assume

knotty sun
#

not just monobehaviour, anything deriving from a Unity Object

upper pilot
#

Makes sense, otherwise unity would get confused 😄

reef garnet
#

Need help with mesh generation, I'm using Unity splines with a custom class to generate a road mesh with T-junctions and intersects and now I want to generate sidewalks but I'm struggling on the intersections and preventing overlap

Any advice is appreciated. Will post my code later as I'm AFK

lapis pebble
#

What would be the best way to limit Vector2 movement to one direction with the newer input system? I am trying to replicate the movement way/feel of an old-gen Pokémon game, and I want for the player to walk in one direction/axis based on the first button pressed + held down, ignoring the other walk inputs pressed after (until the first button is released). Is there an automated way to do this, provided already in the Unity Editor, or is this something that needs to be coded separately?

reef garnet
# lapis pebble What would be the best way to limit Vector2 movement to one direction with the n...

simplest way I can this is on the first button pressed, get the direction and set a bool to true, while that bool is true you don't change the direction, this might need tweaking depending on your desired behaviour as what I've described would work no matter which button is pressed as long as it remains pressed, another one is reading the current input by splitting the Vector into the two axes and say you press forward, then moveInput.y == 1 and as long as it is one then your direction stays Vector2(0, 1) it comes down to stroing what the first move input value was and seeeing if any of that remains the same before changing it

clear sail
#

On the off chance anyone could help me with animations, I've got the code and everything work. But I think I simply don't understand what I'm doing on the animator side. I've got a switch which should interact with a door, the switch animation works but I can't get the door to work with it.

#

I've tried so many different transitions im just at the point I probably need to step away from it.

reef garnet
# reef garnet Need help with mesh generation, I'm using Unity splines with a custom class to g...

Need help with mesh generation, I'm using Unity splines with a custom class to generate a road mesh with T-junctions and intersects and now I want to generate sidewalks but I'm struggling on the intersections and preventing overlap

Any advice is appreciated. Will post my code later as I'm AFK

https://pastebin.com/CZc0j5ix

reef garnet
reef garnet
clear sail
#

It would be correct to add this to the door script?

#

It was more meant to be idle that part you mentioned. I tried just having open and closed and looped between the two but yeah im confused.

reef garnet
#

so you set the isOpen parameter in the code referencing the animator

reef garnet
#

How could I get a list of all the vertices on this loop?

simple void
#

e.g. float3.xy = float2(x, y), float3.xxyy = float4(x,x,y,y,). It also has a bunch of implicit casting to and from int3 and Vector3

limpid ibex
#

Hi, how do you organize object interaction?

For example, on my multiplayer game, I have a common object, a car with screws.

My player can take a screwdriver, and screw in the car's wheels. Would you put the “screwing” script on the wheel or on the wheel itself?

knotty sun
#

as you will need both the wheel and the axel I would put it on the object which is parent of both

steady moat
shell oxide
#

hello

#

im making a level editor

#

how do i snap things correctly?

#

i just want to snap things every block, i have tried a lot of method

knotty sun
#

please type in full sentences

shell oxide
#
RaycastHit hit;
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Cart_Create_FarPlane))
  • I do Raycast
    Then i instantiate
instantiated = Instantiate(BuildingGameObjects[WhatBuildingGameObjectDidWeSelectLast], SnapToGrid(hit.point), Quaternion.identity);

I made a custom Vector3 function

Vector3 SnapToGrid(Vector3 position)
    {
        float x = Mathf.Floor(position.x + 0.5f);
        float y = Mathf.Floor(position.y + 0.5f);
        float z = Mathf.Floor(position.z + 0.5f);
        return new Vector3(x, y, z);
    }

Problem arises, i can place blocks (or anything like spheres) on x,y and z axis
But, when i go oposite to them i cannot place blocks anymore and it just places right inside the object that we hit.

dapper fern
#

Can anyone point me in the right direction about Timeline Signal Emitters and Receivers?

I kinda need to use a Signal that has 3 parameters, but insofar it seems to me that in how Timelines and Signals are set up - you can only ever squeeze just one.

So far I've tried:

  1. Creating a custom signal with 1 parameter (worked, as seen on the screenshot - both int and bool methods appear in Function selection in the signal receiver)
  2. Creating a custom signal with 3 parameters (didn't work, the matching functions do not appear in the receiver selection)
  3. Creating a struct and building an emitter with it (didn't work, same as above)
  4. Creating both an emitter and a receiver that works around a struct (didn't work, same as above)

Is this system even flexible enough to support more than 1 parameter? Am I missing something?

leaden ice
shell oxide
#

isnt it in 2d?

rigid island
shell oxide
#

I HAVE FINNALY GOT IT

#

oh my daysss

#

it was a lot more than what u guys think

#

too much to explain, but thank you for helping, see ya :o

prime ravine
#

Hi !! Is there anyone who wants to help me fix my bugs on a project? I'm trying to create a dialog system in tools on unity, but every time I have a problem with the save graph of the tool... And I don't know how to do it anymore

soft niche
#

Hey, I've got a question regarding a class-based state machine. Can anyone help me?

vestal arch
#

!ask

tawny elkBOT
vestal arch
#

noone's gonna be able to help you if you don't say what you need help with

soft niche
#

Gotcha. If I'm creating enemies that are generally similar (they will all have amble, chase, and attack states), but they have different types of attacks, and some have multiple attacks, should I use one state machine to do this? Or would I need to create a new state machine for each enemy? How would I go about using one machine for different enemy types?

vestal arch
#

you could split it into 2 parts, 1 part being the core state for when to display what behavior, and then another part specifying subbehavior within a specific state (ie, attacking)

soft niche
#

Right, if I understand correctly, I may have that concept already. I have one 'base' class, and then three extra classes derived from the 'base' class which can then transition into each other. I'm not advanced enough in programming to figure this all out myself, so I've been using Finite State Machine tutorials, but none of them seem to have my specific use case. My enemies are all pretty different, but will use some of the same general logic, so I just want to keep it as concise as possible.

vestal arch
#

what are those three extra classes? wdym by "transition into each other"?

soft niche
#

They're the three different states: amble, chase, and attack. Inside each of those classes, whenever a certain criteria is met (i.e. player enters the chase or attack distance) it will transition into the appropriate state using a function (DoState) from the base class.

#

my problem is that I want each state to behave differently for each type of enemy, and I'm not too sure how to implement that

vestal arch
#

so you have 3 separate components, which you're applying all of them to a given enemy?

#

a state machine centralizes the state, doesn't really seem like you have that here, that might make it hard to manage or modify

soft niche
#

If you mean component as in a GameObject component, no, I only put the base class onto the enemy, and the 3 extra state classes derive from that base class, so they can reference each other without having to be attached to a gameobject

vestal arch
#

that doesn't really make sense

#

is the base class aware of the 3 other classes?

#

or what exactly is going on here?

#

or are you mixing/conflating inheritance and composition?

obtuse relic
#

I've spent a while now trying to implement a way to constrain the rotation of a Vector3, and currently I have a beautifully working swing constraint implemented thanks to a stackoverflow post. In the screenshot, the cone indicates the maximum rotation away from the "initial" direction, currently 22.5 degrees. "Final" is the "target" vector constrained to that cone.

soft niche
obtuse relic
#

My question is how can I modify this constraint so that the the maximum swing angle differs between the local x and y axes.
The first screenshot shows the same cone but facing towards the camera. The "Up" vector would be a vector orthogonal to the initial direction, and passed as a parameter when using the method. The second screenshot is what I am trying to do, where the maximum angle along the local x-axis is less than the maximum angle along the local y-axis.

I have tried various ways of achieving this over the last few days but nothing so far has worked correctly. I have looked far and wide online and have just come up empty. My last hope is that someone here may have an idea of how to do this, but if not then I'm ready to consign myself to just using the original "LimitSwing" implementation.

vestal arch
civic girder
#

doesn't seem to be a channel for this, so I'll ask here.
How do I prevent VS from autocomplete if I don't press tab/enter?
In the screenshot, let's suppose I want to name my method "Mo" (bad name, I know, just an example)
The moment I press the ( key, it autocompletes to "onAnimatorMove", forcing me to ctrl+Z then filling it again manually.

vestal arch
obtuse relic
# vestal arch so you're trying to constrain the angle on an ellipse? what about getting the an...

I had briefly considered doing something like that yesterday, but at the time I assumed it wouldn't work if the target direction fell "within" the ellipse (I hadn't slept the night before, so my reasoning skills were missing lol). After thinking about it again though, I guess I could project the target position onto a plane using the normalized direction, and only use the x/y equations in that post if the position falls within the ellipse.

I'll give it a go, thanks!

snow cove
#

Would people consider ChatGPT good for looking at code, and knowing how to fix it? Or are there better bots out there?

reef garnet
#

Anyone know how I can do this? I can generate it along the uncurved area but once it reaches the curve I don't know

#

I'm trying to generate a sidewalk in what is essentially outlining the shape so even if you have a link to somewhere that I can read up on that I'd appreciate it

vestal arch
#

chatgpt is good at being convincing, not at being right. same for other chatbots.

reef garnet
#

it's nice to auto comment your code ʷᶦᵗʰ ᵐᵒᵈᵉʳᵃᵗᶦᵒⁿ

snow cove
#

Ah

vestal arch
#

a lot of chatgpt-generated comments ive seen so far are... questionable

#

chatgpt doesn't really see the "with moderation" part lol

snow cove
#

I've been using ChatGPT for a gun script and while it did have some errors, I've been able to get pretty far

reef garnet
#

essentially anything it tells you, you'd still need to verify it as LLM's work by giving you the statistically most likely answer to the question you feed it

snow cove
#

What does that mean?

vestal arch
#

don't rely on it. you'll need to learn to do stuff yourself as well

snow cove
#

Okay

vestal arch
vestal arch
#

it's a really good guesser, but guessing will never be 100%

reef garnet
#

it's great if you need to ask about code, like a function or something as it can reference the code docs it was likely trained on but overreliance on it is a crutch

#

and it can be a handy starting point, if you encounter a problem you don't know how to solve, ChatGPT might be able to steer you in the right direction to find your answer

snow cove
#

Thank you!

reef garnet
#

In the end it's a tool and so long as you know the tools limitations you can make excellent use of it, but for now your best bets to coding are Google and StackOverflow

civic girder
#

how do I hide all these projects? They're showing up in my solution view

reef garnet
#

oh nvm uncheck the Registry Packages

rigid island
#

The first two is correct , you have to delete them though so they can regen just the ones you marked

#

Otherwise you will still have the same csproj files

reef garnet
#

ah ok

civic girder
glacial gull
#

Hey, i have a game where there is a chat. Whenever the player types in the chatbox, the keys can still trigger movement and other things. Is there a way to disable inputs for everything else when writing in an input field?

vestal arch
#

please don't crosspost

worn flare
#

!code

tawny elkBOT
worn flare
#

does anyone know why my notes are instantiating double and in unexpected positions sometimes based on this code

leaden ice
#

Either line 11 is running multiple times, or you subscribed to the event more than once

worn flare
#

okay

leaden ice
#

Ok - but without seeing more code and understanding when and where for example GreenAudioPeaks() runs, it's impossible to say with the information you've given thus far.

worn flare
#

in update

#

ill share all the code

leaden ice
#

As for the posiiton it will always spawn wherever GreenNoteSpawnPoint.position; is

#

so presumably you've put that obejct somewhere incorrectly

leaden ice
# worn flare in update

In update of what though? We don't even know what script this is, which object(s) it's attached to, etc.

worn flare
#

the green note spawn point stays in the same place ive kept my eye on it

leaden ice
#

clearly not

#

Or if it does, something is moving the notes afterwards

#

Also why do you do this?

        GameObject InstantiatedGreenNote = Instantiate(GreenNotePrefab);
        InstantiatedGreenNote.transform.position = GreenNoteSpawnPoint.position;
        InstantiatedGreenNote.transform.parent = this.transform;```
instead of just:
```cs
        GameObject InstantiatedGreenNote = Instantiate(GreenNotePrefab, GreenNoteSpawnPoint.position, GreenNoteSpawnPoint.rotation, this.transform);```
worn flare
thin marten
#

is there something wrong with my raycast? im trying to do the raycast illustrated in the attached image and return the position at the end if the ray doesnt hit anything, but the ray seems to always hit something even when there is nothing
the bounds colliders are also visible in the image

Vector3 randomDirection = Random.insideUnitCircle.normalized;
Vector3 enemyPosition = _player.transform.position + randomDirection * _enemySpawnDistance;
Debug.Log("trying to spawn enemy at " + enemyPosition);

RaycastHit2D hit = Physics2D.Raycast(
    _player.transform.position,
    randomDirection,
    _enemySpawnDistance,
    LayerMask.NameToLayer("Bounds")
);

if (hit.collider == null)
    return enemyPosition;
else
{
    Debug.Log("enemy raycast hit wall");
    return Vector3.zero;
}
thin marten
#

that fixed it, thank you!

bitter harbor
#

Oops wrong chat.

swift falcon
#

Hey yall. I know this is not the help section BUT I CANT FIND IT FOR THE LIFE OF ME!!!!

So right now I have a prototype ready but every time my friend plays the build it either doesnt load anything/ Loads the models but not the colliders/Loads everything but the scripts/Doesnt open/The Player model starting ascending to the white light

Now I have no idea what this is but it would do this everytime he tried to load it. On mine and everyone else, it works fine. Any ideas???

Specs:
NVIDIA GeForce RTX 3060 Ti

11th Gen Intel(R) Core(TM) i7-117DDF @ 2.50GHz

Windows 11

knotty sun
swift falcon
#

there arent any sadly

cosmic rain
swift falcon
cosmic rain
#

We don't have any power over your friend either.🤷‍♂️

swift falcon
cosmic rain
#

It's like calling a doctor and telling them "my friend has pains in the back, but sometimes they're in the the stomach or chest and sometimes in the left or the right leg, but my friend doesn't want to go to the hospital and do any checks".
Obviously, no one would be able to help your friend even if it's the most professional doctor in the universe.

nova leaf
#

i want to align my shot impacts to the hit normal, but if don't use complex mesh colliders, the impact rotation is wrong on (simple box colliders) and doesn't fit to the mesh, and if i use the shots rotation, and the shot hits a side, the impact rotation is wrong again... any ideas?

leaden ice
dusky lake
nova leaf
#

that's why i said ideas

dusky lake
#

our ideas can vary very heavily depending on what your setup looks like

#

if you have simple meshes it can be easy, if you put a box collider around a complicated mesh that might be nearly impossible

nova leaf
dusky lake
#

but for simple to semi complicated meshes:

  • Put a mesh collider on your mesh dont let your bullets collide with it (untick in collision matrix)
  • Send a raycast from impact point in the direction of -normal of the impact point
  • If that raycast hits the original mesh display the impact hit on that point + figure out the normal of that point
nova leaf
#

the only important thing would be performance with hundreds of shot's hitting every second

dusky lake
#

well my only other idea would be creating an LOD variant of your mesh and using a mesh collider with that

#

is it a deforming mesh or static?

nova leaf
#

static for now

#

i had an idea rn, i could use a capsule collider for impacts (there are no edges to mess the impact rotation up) but wouldn't that also have bad performance? idk how complex round colliders are

dusky lake
#

its sphere > box > capsule > mesh

#

but hundreds of bullets per seconds should still not let unity break a sweat

leaden ice
# nova leaf whatever that means

It means if your prefab is laid out such that its local Up axis aligns with the graphic you want to show, you spawn it with a rotation such that its up axis aligns with the surface normal. Likewise for whatever local direction the prefab is arrayed in

dusky lake
#

unless you are doing other heavy stuff on impact

leaden ice
#

Sphere has the best performance BTW

dusky lake
#

not box?

#

oops

leaden ice
#

Sphere has the simplest math

dusky lake
#

ah right, just a distance check

nova leaf
#

ok i will generate a capsule collider for each unit, and set it on or off based on if the (energy)shield is on or off (the shield impact is a 2d sprite with an offset to the target, that's why the rotation is important) idk if there is a better code way to do it but whatever
hol up but now collisions are broken and collide with the shield... uhh

leaden ice
#

You need layer based collisions

nova leaf
#

ok yes true

onyx ridge
#

my only 3 codes that correlates to shooting or enemy

hidden compass
#

you have Error Pause enabled

#

and theres an error... check that error and you'll have ur answer

onyx ridge
onyx ridge
#

what can be the main reasons my bullet aint registering as an hit / when colliding enemy not taking dmg

spare dome
#

use debug.log to find that out

onyx ridge
rigid island
#

also the 3 dots in your IDE is making a suggestion, give those a look when they appear

onyx ridge
rigid island
#

yes

#

if nothing logs, then the whole method is not running

onyx ridge
rigid island
# onyx ridge

yes click Show potential fixes (btw this is unrelated for current probalem but good for future)

spare dome
#

keep in kind OnCollisionEnter needs a rigidbody to actually get called

onyx ridge
rigid island
#

the function does the same exact thing, just compare tag is more efficient

onyx ridge
#

for some reason its working ish now

#

the hit debug now shows

rigid island
#

the if tag would not change how the OnCollision works

onyx ridge
#

not sure what else i changed to make it work then icl

#

does this code seem correct?

rigid island
#

looks fine

#

maybe would just change < to <=

#

unless you don't want this thing to die if it just touches 0

onyx ridge
#

when it "dies" i think it spawns it out for the other prefab i have for it but not the correct transformation?

this error happens after 4 hits so basically when it "dies"

rigid island
#

if its target.ApplyDamage its probably because you have something hit tagged Enemy that doesn't have EnemyTarget component

onyx ridge
#

applydamage

rigid island
#

you should consider adding a null check first, or if(collision.collider.TryGetComponent(out EnemyTarget target))

#

but fixing the core issue is more important, why is it that something you tagged enemy doesn't have that component

#

if all your enemies will have that component the tag is pretty much useless, you can just check the component directly

onyx ridge
#

tbh im only gonna have one enemy

rigid island
onyx ridge
rigid island
#

since target comes from If component has been found

onyx ridge
#

the enemytarget line

rigid island
#

yes the one doing GetComponent, as TryGetComponent is just a replacement with an null check inside (hence the TryGet and returns a bool if found stored in out )

spare dome
#

target will either return enemy or null

#

so that line is not needed

onyx ridge
#

ah ye i see that has removed that error now

#

but i dont understand taht when it dies why it wont replace the prefab

rigid island
#

prefabs are nothing more than blueprints to a gameobject , they are not really anything else but an asset
they don't exist in runtime

eager fulcrum
#

hey, what am I doing wrong here, I want to take a "screenshot" of my objects and save them in png with transparent background but instead the background is black

 RenderTexture rt = new RenderTexture(512, 512, 24, RenderTextureFormat.ARGB32);
 rt.antiAliasing = 8;

 Camera screenshotCamera = Camera.main;
 screenshotCamera.targetTexture = rt;
 screenshotCamera.clearFlags = CameraClearFlags.SolidColor;
 screenshotCamera.backgroundColor = new Color(0, 0, 0, 0);

 Texture2D screenshotTexture = new Texture2D(512, 512, TextureFormat.RGBA32, false);

 screenshotCamera.Render();
 RenderTexture.active = rt;
 screenshotTexture.ReadPixels(new Rect(0, 0, 512, 512), 0, 0);
 screenshotTexture.Apply();

 byte[] screenshotBytes = screenshotTexture.EncodeToPNG();
 SaveScreenshotOnDisk(screenshotBytes, name, path);

 screenshotCamera.targetTexture = null;
 RenderTexture.active = null;
 Destroy(rt);
 Destroy(screenshotTexture);

 return screenshotBytes;
onyx ridge
spare dome
#

shameless plug lmao

spare dome
onyx ridge
rigid island
#

logging is the way we start singling out issues and making sure things are what we expect them to be

onyx ridge
#

damage is working

rigid island
rigid island
# spare dome shameless plug lmao

I know how painful it is to create a bunch of icons / images from 3D objects by manually screenshotting. Thought one day someone could use the help 😛

onyx ridge
#

it does spawn adn remove the other one

eager fulcrum
rigid island
#

I'd have to double check but probably something to do with the background color / sprite mode chosen

#

since you're rendering a texture and not as sprite? transparency is on by default if sprite2d is chosen as type rather than texture when you explicitly have to check "has transparency"

#

just a guess though

spare dome
rigid island
#

programmer life -> spend 2 days(sometimes) automating something to take a few seconds rather than a few minutes of manual work sadok

eager yacht
#

and then you realize someone else already made it better so you just use their package instead Kappa

dusky lake
onyx ridge
#

its replacing the deadbody now with the correct rotation but its going to a set location and not where the enemy died, any reason why?

onyx ridge
#

when i add this "transform.position, transform.rotation " to the Instantiate code it messes with the rotation of the prefab thats meant to spawn when the enemy dies

rigid island
#

just add that as .rotation then

#

Instantiate(prefab, myPosition, prefab.rotation)

slender sapphire
#

Hello can anyone fix me this error? I get in the error logs that my string array doesnt exist but i declared it outside methods in the class like this (public string[] STRINGS;)

onyx ridge
rigid island
#

i usually have a prefab as Transform if its not a component

onyx ridge
#

just falls through map

#

kinda

rigid island
# onyx ridge kinda

is the rotation correct though? its probably needs offsetting in the position

spare dome
#

it does rotate, it just rotates to the original orientation of the prefab

onyx ridge
#

my prefab settings

#

oh wait nvm.. i forgot the collider..

#

sorry for troubling you guys!

tacit fiber
#

https://paste.ofcode.org/3bzi8vssvxApVZDafVBMfWp

Hey hey!

So i basically wrote this script.
i'm still a noob at unity/C# so i'll write down how it's supposed to work.

I press on indicatorheatmap (which is a big arrow) and it moves to a new position with the cam. ( already did this with click event and works fine)
However i have 3 heatmaps which are 3D graphs that need to start invisible. When i click on the primary button with the indicator heatmap, the first heatmap should popup then press secondary button to cycle between heatmaps that fade in and out with eas in/out for 5 secs.

whenever i click play mode it does NOT start invisble or work at all. Anyone know what im doing wrong?

The heatmaps have mesh renderers. I couldn't add a material for some reason. Could someone check the code ands ettings?

#

this is my hierarchy, Heatmaps is an empty object with the script attached to it.

boreal jewel
#

Hello. This script works fine on the unity play mode, but doesnt work in build. it still rotates, but nothing happens when it hits the player. can anyone help? ty

upbeat fulcrum
#

Hi i have a problem, why my code doesn't work?

#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
public float speed = 5f;
public Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    float v = Input.GetAxis("Vertical");
    float h = Input.GetAxis("Horizontal");

    Vector3 vector = new Vector3(h * speed , 0.0f , v * speed);
    Debug.Log(vector);
    rb.AddForce(vector * Time.deltaTime);

}

}

simple egret
upbeat fulcrum
#

no

#

when i start the game my player don't move

#

i don't know why

simple egret
#

Make sure you attached the script on an active object in the scene

#

And that the script is itself enabled

upbeat fulcrum
simple egret
#

Switch to the Console tab and see what's in there

#

Also since you drag-drop the Rigidbody in the Inspector, you do not need the GetComponent<Rigidbody>() in void Start()

upbeat fulcrum
simple egret
#

The script attached to the object is not the one you're looking at in your code editor. The object and script is active, but you get no errors nor logs. The console is not filtered either

#

Select the script file from Unity and look at its contents with the Inspector. The Obvious™️, make sure you saved your changes

upbeat fulcrum
#

this?

simple egret
#

It's not the same piece of code compared to what you posted, there's no Debug.Log() in void Update()

#

Make sure you don't edit out the code before posting it here, it will mess up the line numbers and/or its behavior

upbeat fulcrum
#

Yes i edit the code

#

I eliminate the debug.log

simple egret
#

Don't. I was using this to see if the code was running or not

#

Put one in Start() and another in Update() and try again

upbeat fulcrum
#

Ok, i'm going to do it

ivory crow
#

I need help with my unity options. When I try to create a C# script there's no option for "Create C# Script"

simple egret
#

It may be in a sub-menu of some sort

mellow sigil
#

It was renamed to "MonoBehaviour Script"

ivory crow
#

ohh okay thanks

#

i appreciate your help

simple egret
#

Good, your code runs

night storm
#

why did Start show so many times though

simple egret
#

Which means you're not adding enough force, or something else (ie. another script) is moving the object

upbeat fulcrum
#

thanks

#

now is turn to do the animations jaja

robust dome
#

code

upbeat fulcrum
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
public float speed = 50000f;
public Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
Debug.Log("Start");
}

// Update is called once per frame
void Update()
{
    float v = Input.GetAxis("Vertical");
    float h = Input.GetAxis("Horizontal");
    Debug.Log("Update");
    Vector3 vector = new Vector3(h * speed , 0.0f , v * speed);
    rb.AddForce(vector * Time.deltaTime);

}

}

robust dome
#

well your cube rolls over because you apply force, you could use rb.MovePosition instead or freeze the rotation of your cube

upbeat fulcrum
#

ok

maiden fractal
#

Would definitely freeze the rotation if you don't need that. MovePosition does not really respect physics as it's no better than transform.position physics wise

robust dome
#

i would not say they are same, even tho MovePosition does not give 100% accurate collisions. it can still be tuned with collision detection which you can´t do with transform position since it only teleports your object.

#

but i would probably not use MovePosition either

#

you will have to see which method you want to use.

leaden ice
#

MovePosition will accurately knock other objects out of the way when used with a kinematic body but the body being moved will not be stopped by other objects

chrome trail
#

I'm trying to plot a point on a NavMesh by trying to use the NavMesh.SamplePosition function. The expectation is that, because the NavMesh is only slightly higher than the plane it's being plotted on, the NavMesh hit I should be getting is the same point only with a slightly elevated y coordinate. For what ever reason, though, the actual NavMeshHit is thousands of miles away and I don't know why or how to fix this. There is a NavMesh space just above the point where it's supposed to be plotted for it to occupy, so why isn't it occupying it?

leaden ice
chrome trail
vestal arch
#

perhaps local vs global position?

chrome trail
#

Unless...

vestal arch
#

it would make a difference if you were basing one check on local coords while the other check was on global coords

#

i can't tell if there's a relevant local position here, but if there was, it'd be at z=-5.67 i think

#

so maybe that's something to check for

chrome trail
vestal arch
#

well, what changed?

chrome trail
#

It's different, but it shifted even further away for some reason

chrome trail
vestal arch
#

thonk shouldn't it be local to the navmesh, if anything?

chrome trail
# vestal arch <:thonk:638524515797827633> shouldn't it be local to the navmesh, if anything?

This is what I'm trying to do

        for (int x = 0; x < 1; x++)
        {
            Vector3 translatedPoint = new Vector3(-projector.size.x / 2f + x * 0.1f, 0, -projector.size.y / 2f);

            if (NavMesh.SamplePosition(transform.position + translatedPoint, out NavMeshHit hit, Mathf.Infinity, NavMesh.AllAreas))
            {
                //Print nodes at the hit point and the theoretical point
                Instantiate(node, transform.position + hit.position, Quaternion.identity);
                Instantiate(node, transform.position + translatedPoint, Quaternion.identity);
            }
        }```
#

The script is attached to a decal projector that is at the same global coordinate as the character it's attached to

#

...Wait

#

Oh I think I see where I messed up

#

There we go. I fixed it

vapid apex
#

for (int x = 0; x < 1; x++)

#

that is 1 iteration only

#

confusing code

chrome trail
# vapid apex confusing code

Because it's supposed to iterate through a grid. This is there so I can test the first instance and the first instance alone

#

Then easily convert to a grid

fallow nimbus
#

I'm trying to programatically render TextMeshPro text to a Render Texture in Unity, that is then attached to and OVROverlay for clear text in VR, using Nothke's RTUtils script (to render to a Render Texture directly without having to create a camera).

Nothke's RTUtils script: https://github.com/nothke/unity-utils/blob/master/Documentation~/RTUtils.md

When starting the program, the text displays for the first frame, but disappears as soon as everything else is initialized (the controllers show). I have been trying to troubleshoot this for a whole day, debugging the program to see if something isn't working as expected, and disabling things like the passthrough renderer to check if the text was being rendered behind somehow.

The only major thing that I've found is that the Mesh Renderer component the TextMeshPro object adds to the GameObject seems to be disabled during runtime, even when I set the renderer of the TextMeshPro object to true each frame. Is there any way to enable/reenable this component programmatically in a TextMeshPro class? I feel like that might be a major factor causing my text to disappear after the first frame. Maybe it's not rendering the text to the Render Texture properly because of this.

Below is the link to the relevant code that renders the TextMeshPro object to the Render Texture and attaches it to the OVROverlay (InitializeLocalization() populates the TextMeshPro object with the relevant text and font). I've also included screenshots of the components on the Startup Renderer object during runtime, along with screenshots of the behavior going on with the OVROverlay on the first frame vs the rest of the time (passthrough object disabled).

https://hastebin.com/share/eguyijigov.csharp

Let me know if any further information is needed.

GitHub

A set of single script utils used throughout my projects - nothke/unity-utils

glacial mountain
#
public class MusicHandler : MonoBehaviour
{
    [SerializeField] private List<AudioData> AudioData;
    [SerializeField] private AudioSource audioSource;

Custom struct (AudioData). Anyone know why it wouldn't show in inspector?

#

my other class works. Just not this new one I made lol

#
using UnityEngine;

public struct AudioData 
{
    public string Name;
    public AudioClip Clip;
        
    public AudioData(string name, AudioClip clip)
    {
        Name = name;
        Clip = clip;
    }
}
#

Nothing fancy

rigid island
glacial mountain
#

ohhh

#

Thanks nav

#

Forgot about that

merry stream
cosmic rain
merry stream
#

serialization between scenes and during crashes

#

im currently doing something similar to serialize SOs and i have issues sometimes with things not saving when alt f4ing etc

#

no idea what causes it since sometimes it works fine

cosmic rain
glacial mountain
#

Is there a way to in editor add a button to game that will end the "play"

#

since application quit only works on compiled exe

covert sentinel
#

Would anyone know why it feels like my player is stuck to the ground for the first jump? It causes them to do a little sticky hop at first.

glacial mountain
#

are you holding it

#

to jump more than once in that vid

spring creek
# covert sentinel

You are using GetAxis which has smoothing. Try GetAxisRaw if you really want a hold button for jumping

#

Personally recommend GetKeyDown though

glacial mountain
#

aha

#
            #if UNITY_EDITOR
                UnityEditor.EditorApplication.isPlaying = false;
            #endif
#

Figured it out

#

Wanted to be able to use/test my quit buttons lol

merry stream
#

not sure what else to do

cosmic rain
dense tree
#

so im making a skills system for a game with 3 classes, each class has two different archetypes. each archetype has 6 passives, 3 abilities, and each ability has 2 specializations. im storing which abilities are set active in a menu in a PlayerSkills singleton.
would i just have to hardcode a bunch of if(PlayerSkills.instance.blah blah) in my player combat scripts?

cosmic rain
hardy pasture
#

Going through the Unity Essentials tutorials. When I double click the code files in Unity, it opens them in Visual Studio but it says that the project is incompatible:

#

Is this normal?

knotty sun
#

right click the solution/project, select reload with dependencies

#

also configure your !ide

tawny elkBOT
hardy pasture
#

Then when I press OK

#

It shows me this web page in the browser

#

And the project is the same in the browser

knotty sun
#

which version of VS

hardy pasture
#

2022

knotty sun
#

then configure first

hardy pasture
#

Thanks, installing Unity workload helped

trim schooner
grizzled grove
#

Okay

rustic ember
#

Hi! I have a cs Dictionary<Vector2Int, List<int>> I want to get a random integer with its respective Vector2Int from the dictionary. Each int should have the same chance of getting picked. I don't know how to achieve this, as every Vector2Int key has a different sized List<int> value

#

The "Element" in the picture represents a Vector2Int key

late lion
#

Alternatively, if you want a simple solution and don't care too much about performance, you can add all the ints and their key to a combined list and choose a random element out of that.

rustic ember
covert sentinel
rustic ember
#

Can't I use structs as default parameters?

somber nacelle
#

Default parameters must be constant. Just make another overload without that parameter that calls this one and passes Vector2Int.one to this

thin aurora
#

Alternatively set the default value to default in order to automatically call new Vector2 if no value is supplied.

rustic ember
glacial mountain
hearty forge
#

Hi!
I need to find the following parameters of a DirectionalLight in HDRP for script.

  • Temperature
  • Intensity Multiplier
  • Indirect Multiplier
    I have searched in HD Additional Light Data(script) but I can't find any parameters with those names.

How can I access those variables via script?

soft shard
# hearty forge Hi! I need to find the following parameters of a DirectionalLight in HDRP for sc...

Its a bit annoying that Unity doesnt always use the same variable name as shown in the inspector - you could try switching the inspector to Debug mode and search for the property that way, filtering by the type or you could also give them specific values and check that way - they should also be listed in a specific order that matches the inspector when viewing the source code for that component so if you know the property above/below the one your looking for you can search that way too - and some of them may require using a Set function from the component and not modifying the property directly

gritty aurora
#

I have a player Rigidbody (physics need to be applied on them with constraints, water, etc so no CharacterController) and their movement is done with AddForce on them.
I'm trying to figure out a way to prevent the player accelerating unrestrained and deal with cases the player trying to slow down if flung without adding to their speed.
I doodled a picture to kinda get across what I'm doing: Red cross is (0,0), top black vector is the player's current velocity, bottom one is the velocity the player is trying to enact, magenta semi-circle is how fast the player can go on their own power, blue is as if I did nothing else to the desired velocity, green is the velocity I want to give to AddForce as it doesn't accelerate the player any faster.

cold egret
#

- Is it possible to re-enable read/write mesh access via the .UploadMeshData method after disabling it? The mesh is procedural

late lion
glacial mountain
#
if (Input.GetKeyUp(KeyCode.Return))

Having issues: In editor (not compiled. haven't tested). But I can't get Input to see enter Key (non numpad) at all

#

Tried KeyCode.KeypadEnter for numpad also

#

and nada

#

Any ideas?

glacial mountain
#

It does work in editor lol ```c#
if (Input.GetKey(KeyCode.LeftShift))
{
if (Input.GetKeyUp(KeyCode.BackQuote))
{
OnToggleDebug();
}
}
if (showConsole)
{
if (Input.GetKeyUp(KeyCode.KeypadEnter))

quartz folio
glacial mountain
#

Oh I just mean Play in Editor

#

IE: Non compiled version.

quartz folio
#

Have you checked that that code is being run, because there should be nothing wrong with KeyCode.Return

glacial mountain
#

aye

#

it is

#
            Debug.Log("ShowConsole state: " + showConsole);
            if (showConsole)
            {
                Debug.Log("In if(showconsole)");
                if (Input.GetKeyUp(KeyCode.Return))
                {
                    Debug.Log("return key up event");
                    OnReturn();
                }
            }
#

I'm curious if its because its a gui.textbox, which I don't know why input would matter

#

I mean TextField lol

#

ah yea. works when not focused. weird

glacial mountain
#

weird lol

#
                    if (e.type == EventType.KeyDown)
                    {
                        Debug.Log(e.keyCode == KeyCode.None);

catches return/numpad enter in gui

glacial mountain
#

for quick debug menu

#

well

#

console

#

quick rect + textfield that focuses control there when key group is pressed, then obviously handles input based on return

quartz folio
#

If you're reading from OnGUI you need to use Event, what Navarone linked earlier

#

Though I would recommend using UIToolkit instead of IMGUI for menus like these

glacial mountain
#

I'll look into UI toolkit

glacial mountain
#

Whats wrong with IMGUI btw? I don't typically use Unity, but I have used imgui in personal projects a bit.

quartz folio
#

It's being removed because UI Toolkit is the future of both Editor and Runtime UI in Unity

glacial mountain
#

IE: I use unreal. Only using this out of force by class

#

ohhh

#

Makes sense

#

I appreciate you telling me.

#

Basically it's outdated

#

in Unity anyways

quartz folio
#

It'll stick around for a while, because Unity 7 is still ages away, and Unity 6 will have a long life, but as UITK is the future and has been a great replacement for debug menus for many generational releases now, I would avoid it

glacial mountain
#

Essentially doing a test run of a menu similar to sims

#

or other games with the ~ debug menu

vale wharf
#

Having an issue with my custom terrain editor where if I try to sculpt multiple cells across two chunks borders, the cells at the borders of each chunk will be higher than they should (see gif).

I think this happens because I have code to prevent the borders of adjacent chunks from having gaps due to height differences which causes the cells at the borders to be updated multipel times in the situation in the gif.

The sculpt tool sets the heights of cells like this:

foreach (var cell in selectedCells) //selectedCells is a dictionary with a key/value pair of cellPos, chunkPos
{
    //Get the chunk
    MarchingSquaresChunk chunk = t.chunks[cell.Value];

    //Cell index in the heightmap array
    int idx = chunk.getIndex(cell.Key.y, cell.Key.x);

    float newHeight = chunk.heightMap[idx] + dragHeight; //drag height is the amount of pixels the mouse has moved up or down

    t.SetHeight(cell.Value, cell.Key.x, cell.Key.y, newHeight);
}

and SetHeight looks like this:

public void SetHeight(Vector2Int chunk, float cx, float cz, float height)
{

    MarchingSquaresChunk c = chunks[chunk];
    c.drawHeight((int)cx, (int)cz, height);


    //Do we have a chunk to the left and are we setting a cell on the left edge?
    var chunkLeft = chunks.TryGetValue(new Vector2Int(chunk.x - 1, chunk.y), out var leftChunk) && cx == 0;
    if (chunkLeft)
        if (leftChunk.heightMap[leftChunk.getIndex((int)cz, dimensions.x - 1)] != height)
            SetHeight(new Vector2Int(chunk.x - 1, chunk.y), dimensions.x - 1, cz, height);

    var chunkRight = chunks.TryGetValue(new Vector2Int(chunk.x + 1, chunk.y), out var rightChunk) && cx == dimensions.x - 1;
    if (chunkRight)
        if (rightChunk.heightMap[rightChunk.getIndex((int)cz, 0)] != height)
            SetHeight(new Vector2Int(chunk.x + 1, chunk.y), 0, cz, height);

    var chunkUp = chunks.TryGetValue(new Vector2Int(chunk.x, chunk.y + 1), out var upChunk) && cz == dimensions.z - 1;
    if (chunkUp)
        if (upChunk.heightMap[upChunk.getIndex(0, (int)cx)] != height)
            SetHeight(new Vector2Int(chunk.x, chunk.y + 1), cx, 0, height);

    var chunkDown = chunks.TryGetValue(new Vector2Int(chunk.x, chunk.y - 1), out var downChunk) && cz == 0;
    if (chunkDown)
        if (downChunk.heightMap[downChunk.getIndex(dimensions.z - 1, (int)cx)] != height)
            SetHeight(new Vector2Int(chunk.x, chunk.y - 1), cx, dimensions.z - 1, height);
}

Does anyone see any logic issues which might be causing the behaviour in the gif?

glacial mountain
#

The double layering at the split?

vale wharf
#

yes

glacial mountain
#

Its reading both cells from look of it

#

So its doubling up

#

well let me rephrase

#

is the big square a chunk and each minibox a cell

#

or other way