#archived-code-general

1 messages · Page 36 of 1

surreal phoenix
#

ok so i found my solution to this. the asset doesn't show up under the menu provided by the '+' button in the scene inspector like the docs say. it actually shows up under the asset>create menu in the menubar...

hexed geode
#

ok so i'm still very confused
let me elaborate on a few things:
my game isn't exactly a rhythm game but more of a bullet hell game i'd actually say, stuff like lasers appear at certain positions and at certain timings and with certain attributes, so how would i put all of that into something i can then read and build?

cedar jolt
leaden ice
# hexed geode ok so i'm still very confused let me elaborate on a few things: my game isn't ex...

That's the challenge you need to solve, and it really doesn't matter that it's not a rythm game.
Just imagine a list of instructions:
"at time 1s, spawn a red laser at position xyz facing direction xyz",
"at time 2s, spawn a green bomb at position xyz with a 5 second timer",
... and so on

This is basically something like List<SpawnInstruction> in code. (where SpawnInstruction is a class you make).
Get it?

hexed geode
#

oh yeah that makes so much sense

leaden ice
#

it's not trivial, it's a good amount of work, but that's what would go into it

hexed geode
#

that sounds quite fun

leaden ice
#

and you need to be able to read/write these instructions to files

cedar jolt
#

If you want to do something like that I would recommand implementing the Command Design Pattern to do the timings

hexed geode
#

to have the song and any of the sprites be able to be saved with the level and easily shared

hard sparrow
#

Is using reflection like this a fine thing to do, or the kind of thing you want to avoid if possible?

hard sparrow
#

Basically I'm asking if this is code smell

#

chatgpt wrote it

leaden ice
#

it's setting the fields to their own values

hard sparrow
#

it's basically just copying a prefab as a component

polar marten
#

i got one!

leaden ice
#

beyond that it doesn't seem to do anything more than AddComponent

leaden ice
polar marten
#

i'm only hitting 1/3 i think

leaden ice
#

I would expect a parameter for the thing to be copied in that case

hard sparrow
#

it's a situation where you want to add a component of DerivedClass (generic) and propogate its abstract fields

leaden ice
hard sparrow
#

Well basically I'm applying a status effect by just feeding in an enum StatusType. Then a class fetches the prefab of the appropriate status and adds a component of DerivedType (the particular status), then fills the abstract fields

#

it's probably not the best architecture, but it should work fine

#

I don't know anything about reflection though, or if it's used that much

leaden ice
#

The JSON string is fishy but Unity doesn't give us access to the binary form of its serializer sadly

hard sparrow
#

chatgpt, make a new unity with public binary forms of the serializer

#

(this'll take a sec)

cedar jolt
#

I am curious to see what I am doing wrong here. Basically, I want to have a raycast that goes up and down at certain timing to see if the cube is at the right place on the map/on the right object.

Does someone have an idea of what is happening here on the coordinate ?

leaden ice
#

you're giving it two positions

#

maybe use DrawLine instead

#

which does expect two positions

cedar jolt
#

So what would be a direction in this context?

leaden ice
#

a direction... is a direction

#

like Vector3.up

#

is a direction pointing up

#

transform.up is a direction that is the object's local idea of "up"

cedar jolt
#

Ho thank you!

leaden ice
#

you're adding in transform.position to that

#

which is... not right

hexed geode
leaden ice
#

it will be tricky when you want to have different types of objects though

#

but that's the basic idea yah

cedar jolt
hexed geode
leaden ice
tired egret
#

how can i know in code when I just saved something in Visual Studio, and while the Unity game/editor is running I click into it and trigger the "reload scripts" popup?

modern creek
#

i've got a UnityUI scroll rect with some inertia but it also responds to scrollwheel input. If you "flick" the rect and it's .. inertia-ing, scrolling with the mouse wheel will click the rect up/down one click, but then keep on moving from the inertia. is there any built-in functionality in this component to prevent that? or do I need to hook OnValueChanged and stop the movement

tired egret
#

i think it's called "hot reloading"?

modern creek
#

maybe this behaviour is the expected behaviour, I dunno, actually

zinc parrot
#

so say I have a compute shader with a #define in it
is there any way to change the #define automatically from script? I want to be able to go between HDRP and Built In without seperate code for both

polar marten
# modern creek

you'll have to modify the ScrollRect source to kill the inertia :/

modern creek
#

it's probably fine.. it's a little clunky but i think either people are gonna use the scrollwheel or click and drag, but not both (for windows)

severe maple
#

i'm guessing it's not possible to have dictionaries created in editor mode accessed in play mode. My editor mode populated dict is empty once play starts even though I never empty it in runtime

modern creek
#

as far as I know you can? i don't tend to expose dictionaries in the editor

leaden ice
severe maple
#

thanks

ripe vale
#

Anybody here can point to a way to make the player follow along the wall when moving against it ?

#

What I tried only works if the player is pressing w+a or w+d etc

#

wanted to know if its possible to only press w and slowly slide right or left depending on the angle

whole parrot
#

Which one of you is a rigidbody expert?

prime sinew
whole parrot
whole parrot
prime sinew
#

So you're going to waste the time of everyone who bothers to get to you. What if they don't know?

whole parrot
#

If you're in a discord, chatting, chances are you have time to waste and I am not going to be rude

#

Blatantly asking outright is rude

prime sinew
#

It's not really. I suggest you read that article

somber nacelle
whole parrot
#

Anyway, Im gonna go to the other chat. I just need help, not an argument

prime sinew
#

I get the intention, but this is a text medium. You're not interrupting anyone

rain minnow
tired egret
#

it takes 3-4 mins to run my game in editor 😦

simple echo
#

Hello !

#

I am currently trying to code a depth first search in Unity to generate a maze

#

I have the code with me given by my teacher but i am confused in some places and would gladly appreciae some help

#
  1. Why do I need a private field to generate random numbers?
tired egret
#

he asked that question? (number 1)

simple echo
#

what would this block of code do?

#

why am i shuffling the directions ?

#

and why is it %4?

simple egret
#

To pick a random direction to carve into

simple echo
simple egret
#

And the modulus would be to get the opposite cell's wall to remove

#

And you get a random direction so you don't always carve towards the right for example

#

If you didn't shuffle, it would be biased because it would always start carving towards the same direction, creating weird layouts

#

Got the logic for the %, it indeed gets the opposite side of the adjacent cell.

+ 2 + | + 2 +
1   3 | 1   3
+ 4 + | + 4 +

Say you carve right, that side is labeled "3". To get the opposite wall on the cell on the right, it does 3 + 2 % 4 which gives out 5 % 4 => 1. That's indeed the wall on the left, of the cell on the right!

simple echo
simple echo
simple egret
#

The percent operator is "modulus", it's the remainder of a division

#

5 / 4 => 1, remaining 1

simple echo
#

also what do you mean by "you" in "you wont carve into a direction?"

simple echo
simple egret
#

Yep

simple echo
#

thank you so much for all your help! i truly appreciate your time

simple egret
#

And by "you" I meant the algorithm lol

simple echo
simple egret
#

If it always carves in the same direction you'll get a lot of straight lines, and that's not very maze-ish

#

That's why it needs to shuffle the directions

#

It eliminates as most straight lines as possible

#

Actually yeah your maze will be all straight if there's no shuffling at all, it won't be random aside from the start point

rocky void
#

Hey all, I'm having an odd problem here. I had a script written for a recoil system and had it attached to a firearm, all was fine. Out of nowhere the attached component changed to "Script" and said please fix any compile errors in the script. I hadn't changed anything on that particular script and there's no compile errors in it at all. I can't add the script as a component anymore and I'm going crazy trying to understand why

simple egret
#

Make sure the class name matches the file name it's in

#

A class Recoil must be in a file Recoil.cs

#

If that's the case already, move the file to another folder within Unity, and back. This will force Unity to do a full compilation, hopefully fixing the issue in the process

#

Sometimes it doesn't pick up changes made to your code

cosmic rain
rocky void
simple egret
cosmic rain
#

If there's no compile errors, then it must be the file/class name as SPR mentioned.

rocky void
rocky void
cosmic rain
rocky void
#

I can't think of anything else as it does wonky things sometimes that need fixing and I definitely didn't do that myself

cosmic rain
#

Yes. Abstract classes can't have instances.

#

Intellsense doesn't do something like that though.

rocky void
# cosmic rain Yes. Abstract classes can't have instances.

Mine does lol. It sometimes suggests alternate code when I highlight something and pressing tab instantiates it. I sometimes run back through something and find an incorrect implementation or variable. I've had it suggest names that don't exist yet when declaring variables that sometimes throws me off

cosmic rain
#

Are you using Copilot or something? I don't think the VS2022 ai assistant gives suggestions for editing existing code...

#

In fact, I don't think copilot does that either.

rocky void
#

I recently started with VS2022 as VS2019 was giving me an unusual amount of problems and warnings. Still a list of warnings with VS2022 but my intellisense by default suggests new variables as I'm naming them and sometimes creates its own

#

It doesn't seem to do it in an established document, but upon making a new script it suggests naming conventions for me

cosmic rain
#

Yeah, that's the ai assisted suggestions. Although I've never had it make changes to existing code.

rocky void
#

It usually only does it if I accidentally hit tab to autocomplete though sometimes it does insert code I didn't want, such as [SerializeField] that I need to erase before typing a regular variable declaration

leaden ice
#

I found it very annoying personally

rocky void
leaden ice
#

you still get regular intellisense without the AI stuff

rocky void
cosmic rain
#

I do find it useful. Especially if I have to deal with somewhat repeating code.

polar marten
#

did microsoft make intellisense show copilot completions by default?

cosmic rain
#

It's not copilot afaik. It's not pretrained on a large set of code. It gets trained on your project as you develop if I get it right.

#

Maybe not trained. But it doesn't give any complete code suggestions. Mostly just based on stuff that you already have in your project.

void basalt
#

I'm having a very very odd problem. I have a humanoid animated character. I have a capsule collider on it. Whenever I enable the animator, the character like offsets itself

#

and like raises himself above the capsule collider. Only happens when I enable the animator

#

root motion is off

leaden ice
#

root motion off doesn't mean "don't animate the root object"

#

it actually kinda means the opposite. It means "allow the root object to be animated while still allowing external motion in the world from other means

void basalt
#

Alright thanks

solemn raven
#

hey,
is it possible to check if objectA and objectB colliding from objectC ? .. meaning the check function is on objectC not on A nor B??

leaden ice
solemn raven
#

alright , thanks 🙂 , i had an empty script i was gonna add the function there but alright 😄

modern creek
#

I might have a memory leak or some high memory use in one of my animations, so I'm wondering what the best approach to tween a value in a particle system over time would be? My current approach:

        public IEnumerator BrakesCoroutine()
        {
            const float BrakesAnimationDuration = 6f;
            Sequence seq = DOTween.Sequence();
            seq.Insert(0, DOVirtual.Float(MovingStarsEmissionRate, 0, BrakesAnimationDuration, (f) => SetMpsEmissionRate(f)));
            yield return seq.Play().WaitForCompletion();
            ResetMPS(); // Sets back to starting value
        }
        private void SetMpsEmissionRate(float f)
        {
            var mpsEmission = MovingParticleSystem.particles[0].emission;
            var mpsEmissionROT = mpsEmission.rateOverTime;
            mpsEmissionROT.constant = f;
            mpsEmission.rateOverTime = mpsEmissionROT;
        }

Is this leaky or problematic..?

cosmic rain
#

Not really. At least not by itself. Where do you start the coroutine?@modern creek

modern creek
#

It's a little more complex than I can describe in a sentence, but .. basically a singleton is emitting a static event.. I'm just sorta confused by this leak, if it is one

#

I can't repro it on my machine but one of my coworkers can consistently crash his machine with this area of code

#

his unity.exe just stops responding and dies - no stack trace, no logging, just.. stops rendering, uses more and more memory, then dies

#

normal looks like this:

#

exact same version, workflow, etc

modern creek
cosmic rain
#

Does that happen in a build only?

gloomy swan
#

is there a way to make your character move the same speed as navmesh agent when they're set to the same number?

#

say navmesh agent speed is 5 and the character I control also set the speed to 5, then they will have the same speed

cosmic rain
modern creek
#

Yeah.. he's running the same version as I am.. his logs just say "Acceleration requested" and then stop

#

I'm not entirely sure it's here that's the problem, but .. this is the last line in all his logfiles so it seems like it is? I'm not having much success assessing this one

#

the "First tap event invoked" line is the singleton emitting the event

cosmic rain
#

Does his game also freeze?

modern creek
#

hm, it might be another issue.. I've got this one script that's doing a long running coroutine (30-60 sec) and restarting itself (basically the ship slowly "wobbles" around the center). When you get to a destination though it starts a new set of coroutines (pseduocode below):

public void OnArrivedHandler()
{
  StopAllCoroutines();
  StartCoroutine(WobbleShipCoroutine()); // <-- does this not work because of the previous call to stop?
}
#

yes, his game freezes.. sorta.. the music keeps playing, but the update loops don't come anymore (screen goes white, game freezes)

#

it feels like an infinite loop but.. i'm running the exact same code so i don't understand how

#

in fact, the codebase is guaranteed identical since the multiplayer server gates connection based on version/build

#

I'm doing that sort of thing elsewhere - is it possible that those start coroutine calls are ... multiplying? 😛 my early exit clause there isn't returning, but i don't see any of these error messages (w(""))

cosmic rain
#

For starters you could use the memory profiler to find out what's eating the memory. That would probably give a clue on what's going wrong.

modern creek
#

yeah i've been playing with it but it's .. not showing me anything obvious.. you're talking about the com.unity.memoryprofiler one? experimental?

cosmic rain
modern creek
#

Yeah.. I think therein lies the rub - can't repro it on my machine .. I hate to be a meme but "it works on my computer" makes it pretty hard to debug this

#

Ah well, thanks for having a look.

modern creek
#

nah he's a designer

#

the lack of any log messages or crash dmp for him to give to me sorta hamper it

#

if it just straight up crashed, at least I'd have a stack trace to explore

dusty lava
#
var results = persons.GroupJoin(
    phones,
    person => person,
    phone => phone.Person,
    (person, phoneEnum) =>
        new {
            person.Name,
            PhoneNumber = string.Join(',', phoneEnum.Select(x => x.PhoneNumber))
        }
);

hey hello! this is an example of linq group join
i dont understand why is the last parameter IEqualityComparer but it isnt implementing a proper comparison method
please help?

full scaffold
#

(2D) How do I pass in a rotation to a bullet towards the player? I have this right now but it only goes 90 deg to the right no matter where my player is to the enemy.

IEnumerator ShootBullet()
    {
        Vector2 direction = _player.transform.position - this.transform.position;
        Instantiate(_bullet, this.transform.position, Quaternion.LookRotation(_player.transform.position, transform.right));
        yield return new WaitForSeconds(reloadSpeed);
        _isShooting = false;
    }
cosmic rain
dusty lava
cosmic rain
modern creek
#

Hm.. Is there anything wonky about how coroutines work and are scheduled? Is it possible that I'm starting a coroutine but it's just getting added to some list for later processing, which doesn't run or is dropped for some reason - and so the later calls (which normally are fine because the first line of the coroutine checks to see if it's already running) just stack up more coroutines starts..?

#

ie:

void Update()
{
  if (!isRunning) StartCoroutine(SomeCR()); // could this fail or add multiples under load..?
}

private IEnumerator SomeCR()
{
  isRunning = true;
  ... do some stuff ... 
}
full scaffold
cosmic rain
void basalt
#

Suppose I have an animated first person character. When the camera is parented to the head, there's a lot of jarring shaking going on. How is this normally stabilized? Two skinned mesh renderers with one animation on and the other off and just have them overlap each other? With the camera parented to the non animated invisible skin?

modern creek
cosmic rain
modern creek
#

yeah, i never do that

#

a long time ago I used to make these monolithic "screen" monobehaviours that orchestrated all kinds of nonsense.. coroutines.. tweens.. particle effects, etc. When they started hitting like 2k lines and being super hard to debug I started going hard towards the "one MB for one tiny little thing" approach and it's been much better

cosmic rain
#

But as far as coroutine execution goes, it acts as a normal method at StartCoroutine. When it reaches the yield return, it stops execution and continues it later depending on what was returned.

modern creek
#

K.. I wasn't sure if "startcoutine" internally just added the method to a list of delegates for later (in the frame) execution

#

but that would probably be crazy confusing if you were doing things like

StopAllCoroutines();
StartCoroutine(someCR());
StopAllCoroutines();

private IEnumerator someCR()
{
 log("hello"); // never happens in this upsidedown world
}
cosmic rain
#

Yeah, if it was like that there would be numerous issues.

astral oriole
#

Hey, I have been having issues trying to get only one of the little guys going to each cube, but I can't figure out how to reference each specific cube prefab

#

so they all just run to the latest cube

#

how should I go about making it so one goes to each cube?

leaden ice
#

also they're not prefabs when they're spawned

#

only the one original in the assets folder is a prefab

astral oriole
#

oh i see, thank you

mental reef
#

Hello. I am new at using C# and I'm following a series on YouTube but unable to continue due to an issue I have faced. Am I able to post it here?

lone vector
#

Hey guys, quick good-coding-practise question about how to handle values that get set for x time by multiple sources:
Say I've got a bool that represents whether a player's inputs should be read or not. And this bool can be temporarily set to true by a bunch of different scripts and functions and such. What is the correct way to do this? One issue could be if 2 different coroutines are running, one sets it to true, then another sets it to true just as the first one was about to set it to false. How is it meant to know something else tried to set it to true since it did? I've thought of a couple of different approaches, I just wanted to ask which was the best.

  1. Create an int buffer that counts up every time that the value is changed, and then each coroutine stores its own local value to compare against, and will break itself if the buffer value is higher than the local one.
  2. Create a bool for each individual coroutine which a function then checks and essentially does an OR check on every bool.
    Or alternatively, please tell me any other approaches that may take advantage of C# features I wasn't aware of. I'm not looking for the most optimised or anything, just the easiest to read and cleanest solution. Thanks for hearing out my question.
leaden ice
astral oriole
#

damn praetor sounds like a pro

lone vector
#

How would that prevent the issue I mentioned though?

leaden ice
#

I don't really understand the issue because you are talking about some stuff from your code without context

lone vector
#

you'd still have multiple versions of the one coroutine running simultaneously

#

okay i can try write up a quick example

leaden ice
#

you'd have to explain what this coroutine does etc

#

because we don't have the context

lone vector
#

what you did mention did give me an idea id never had though

#

ill keep that in mind for what i write in the future at least

#

hang on ill write what I mean

leaden ice
#

What I'd say with the limited info i have here is that the obejct that owns this bool should also be managing these coroutines probably

#

but yes please do write up your example

astral oriole
#

hey praetor I have a quick question, what's the easiest way to make the list for the gameobjects spawned from the prefab, and how to reference each one?

#

I'm a little new to unity

leaden ice
#

List<GameObject> instances = new();

#

and when you spawn an instance you do:

GameObject newInstance = Instantiate(thePrefab);
instances.Add(newInstance);```
astral oriole
#

awesome, thank you

#

new toys

lone vector
#
public class Problem : MonoBehaviour
{
    private bool freeze;
    public IEnumerator TempFreeze(float time)
    {
        freeze = true;
        yield return new WaitForSeconds(time);
        freeze = false;
    }
}```
#

thats the problem

#
public class Example1 : MonoBehaviour
{
    private bool freeze;
    private int tempFreezeIndex;
    public IEnumerator TempFreeze(float time)
    {
        tempFreezeIndex++;
        int ownIndexBuffer = tempFreezeIndex;
        freeze = true;
        yield return new WaitForSeconds(time);
        if (ownIndexBuffer == tempFreezeIndex)
            freeze = false;
    }
}```
#

thats my first solution

#

its messy

leaden ice
#

this is definitely overcomplicating it

lone vector
#

whats the better way to avoid clashes like that then

leaden ice
#

well first let me ask you

#

when someone wants to freeze for x seconds

#

and there's already a freeze going on

#

what do you want to happen?

#

how long should the freeze last

lone vector
#

that needs to be variable

leaden ice
#

let's say there are y seconds left on the existing timer

#

and they want to freeze for x seconds

#

do we freeze for x seconds?
Or x + y?

lone vector
#

oh you're right

#

i could just use Time.time

#

and store that as a float

leaden ice
#

not what I'm saying exactly

#

just asking a question

lone vector
#

we just want to remain frozen until nothing wants it to be frozen anymore

leaden ice
#
private bool _isFrozen;
public bool IsFrozen => _isFrozen;
private Coroutine currentCoroutine;

public void Freeze(float time) {
  StopCoroutine(currentCoroutine);
  currentCoroutine = StartCoroutine(FreezeCor(time));
}

private IEnumerator FreezeCor(float time) {
  _isFrozen = true;
  yield return new WaitForSeconds(time);
  _isFrozen = false;
}```
#

so this is a very simple way

lone vector
#

oh

#

id never considered integrating a StopCoroutine before

leaden ice
#

as I said - this thing should be managing the coroutine(s) and the freeze variable

#

all internally

#

only allow access through very specific public things

lone vector
#

hang on let me write one more thing real quick

leaden ice
#

also importantly, this object is starting the coroutines itself.

astral oriole
#

hey praetor, am I able to reference each specific spawned gameobject? like name them worker1, worker2 etc?

lone vector
#

is there a reason I shouldn't do it this way instead?

leaden ice
#

that's not the worst idea.
I generally just shy away from using Time.time in general for floating point precision reasons.

lone vector
#

yeah thats also true

leaden ice
lone vector
#

is it likely you'll run into that though

#

oh you can get the time as a double???

leaden ice
void basalt
#

How are first person characters generally done? I can't parent the camera to the animated head because then you get really jarring visuals. Is it common to use 2 character models? One invisible without animations and the other visible with animations? And then the camera goes on the invisible non animated model?

leaden ice
#

depending on how accurate you need it to be

lone vector
#

i'd imagine time as a double would get into ludicrous amounts of time though right

leaden ice
#

yeah timeAsDouble would be fine

lone vector
#

sweet

#

i feel like the approach I took reads a little clearer

leaden ice
#

it's a good approach

#

it's very efficient too

lone vector
#

😁

leaden ice
#

no need to run any code every frame

lone vector
#

i feel like a genius for the solution you led me to

#

lmfao

leaden ice
#

(all coroutines require at least one check every frame

lone vector
#

thats also true

#

thank you very much for the help

leaden ice
void basalt
#

and to see the lower half of your body

leaden ice
#

I see

full scaffold
#

I'm trying to visualize the bounds of a sprite by drawing gizmos but this one isn't appearing:

private void OnDrawGizmos(){
        Vector3 top_right = new Vector3(_length, 0, 0);
        Vector3 bottom_right = new Vector3(_length, _lengthY, 0);
        Vector3 bottom_left = new Vector3(0, _lengthY, 0);
        Vector3 top_left = Vector3.zero;
        
        Gizmos.color = Color.yellow;

        Gizmos.DrawLine(top_right, bottom_right);
        Gizmos.DrawLine(bottom_right, bottom_left);
        Gizmos.DrawLine(bottom_left, top_left);
        Gizmos.DrawLine(top_left, top_right);
    }
leaden ice
elfin vessel
#

When I build my project with Addressables, it complains about a bunch of Unityeditor namespace stuff, because it doesn't compile with the UnityEditor namepsace. Is there a define symbol for compilation?

leaden ice
elfin vessel
leaden ice
#

make an assembly for the editor only code and have it reference your main assembly

elfin vessel
#

oh, i see

lone vector
# lone vector ```cs public class Example2 : MonoBehaviour { private float m_FreezeTime; ...

I realise this solution doesn't accommodate for when it needs to be frozen for an indefinite amount of time, so I've gone and changed the frozen code:

public bool frozen
{
    get { return Time.timeAsDouble > m_FreezeTime; }
    set { m_FreezeTime = value ? double.MaxValue : 0; }
}```
In my case there aren't a lot of clashes between indefinite-time-freezes, but I think i might add another value to represent indefinite time freezes instead just so indefinite time freezes dont overwrite whatever is happening with how long its frozen for the definite-time freezes
full scaffold
lone vector
distant glen
#

How do I check if a list contains an object, rather than a specific instance of an object?

leaden ice
# distant glen How do I check if a list contains an object, rather than a specific instance of ...

if you want a definition of "sameness" besides "literally the same object in memory" you need to make your class or struct implement this interface:
https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=net-7.0
List will respect this equality

distant glen
#

Inventory.Contains(item) only seems to return true if the item being checked is the same as the instance of the item stored in the List. Two identical items won't return true and I want it to, if that specific item is contained in the List, regardless of its instance.

astral oriole
#

Hey praetor, quick question, for the list is there an easy way to say spawnedobject1 do this, spawnobject2 do this etc?

#

im just having trouble numbering them

leaden ice
#

typically you would be doing that in a loop or something though

#

very rare to hard code numbers like that

astral oriole
#

yeah idk if im an experienced enough coder to NOT hard code this lol

leaden ice
#

If you're hardcoding it it kind of defeats the purpose of the list

astral oriole
#

i want each of the spawned objects to have its starting position on top of each spawned objects from a different list lol

#

hard to wrap my head around how to do that properly

leaden ice
#
for (int i = 0; i < differentList.Count; i++) {
  thisList[i].transform.position = differentList[i].transform.position;
}``` something like this?
astral oriole
#

hmmmm

leaden ice
#

unclear if you're trying to spawn these things in the loop or just position them

astral oriole
#

this is the code im looking at. essentially for each woodhut placed i want a worker to spawn at it

#

building.targetpos1 is set to the centerposition of the woodhut, but if there's multiple woodhuts then all the workers spawned get placed at the most recent woodhut

leaden ice
#

what is Building? And what is targetpos1?

#

(generally it's a red flag when your variables have numbers like that btw 😉 )

astral oriole
#

lol yeah, i kinda half followed a tutorial then did my own thing

leaden ice
#

your variable names are kinda crazy

#

why is a variable that seems to represent the position called "worker"

#

that's so confusing 😵‍💫

#

how about "workerPosition"?

astral oriole
#

lol yeah that seems better

#

'Building' is my first list, where you can place different buildings

#

but for the specific building 'woodhut', i want a worker to spawn at the center of it

#

but when there can be more than one woodhut placed, that's when all the workers go to the last placed woodhut

sterile tendon
#

does anyone know why this code doesn't work? all the directories exist

    void Shift()
    {
        Debug.Log("Attempting shift");
        AssetDatabase.DeleteAsset(@"C:\Users\Cameron\watchmealways\Assets\Scripts\script.txt");
        AssetDatabase.DeleteAsset(@"C:\Users\Cameron\watchmealways\Assets\mp3Files");
        AssetDatabase.MoveAsset(@"C:\Users\Cameron\watchmealways\Assets\Scripts\newscript.txt", @"C:\Users\Cameron\watchmealways\Assets\Scripts\script.txt");
        AssetDatabase.MoveAsset(@"C:\Users\Cameron\watchmealways\Assets\newMP3s", @"C:\Users\Cameron\watchmealways\Assets\mp3Files");
    }
leaden ice
#

what happens?

potent sleet
sterile tendon
#

nothing

leaden ice
#

Debug.Log

sterile tendon
#

yeah it prints

#

that's why I put it in

#

oh I have an idea I'll put one at the end

#

maybe it just takes a while? idk

leaden ice
sterile tendon
#

ohh

#

thanks

#

that makes sense

potent sleet
#

Oh AssetDatabase wants file extensions, but Resources class doesn't

sterile tendon
#

wait this is weird, everything works except the renaming the directory

    void Shift()
    {
        Debug.Log("Attempting shift");
        AssetDatabase.DeleteAsset(@"Assets\Scripts\script.txt");
        AssetDatabase.DeleteAsset(@"Assets\mp3Files");
        AssetDatabase.MoveAsset(@"C:Assets\Scripts\newscript.txt", @"Assets\Scripts\script.txt");
        AssetDatabase.MoveAsset(@"C:Assets\newMP3s", @"Assets\mp3Files");
        Debug.Log("Finished!");
    }
#

wait and renaming the script

#

but the deleting works fine

indigo drift
#

I updated my game to unity 2022 and now jsonconvert doesn't exist anymore? 😭 I have the newtonsoft package downloaded and it says it cannot be found

elfin vessel
dusk oyster
#

help pls, I'm new to programming, so does anyone know a GOOD tutorial to make the imputs for my 2d fighting game? I've tried to follow a couple of tutorials but most of them do weird things.

#

the animations are cut off or something like that

fringe wraith
#

guys how to get the device id for admob
systeminfo.deviceUniqueIdentifier is not working
how to define device id for android platform?

soft shard
# dusk oyster help pls, I'm new to programming, so does anyone know a GOOD tutorial to make th...

If you are working with the "new" input system, I would suggest tutorials from samyam: https://www.youtube.com/watch?v=m5WsmlEOFiA&list=PLKUARkaoYQT2nKuWy0mKwYURe2roBGJdr

However, animations being cutoff may be unrelated to the input system, unless your "cancelling" your input early, that will depend on how you have your project setup

How to use the new input system in Unity! I go over installing the package, the different ways to use the input system, and the recommended way!

📥 Get the Source Code 📥
https://www.patreon.com/posts/55295489

►🤝 Support Me 🤝
Patreon: https://www.patreon.com/samyg
Donate: https://ko-fi.com/samyam

🔗 Relevant Video Links 🔗
ᐅALL of my Input System...

▶ Play video
fringe wraith
#

when i build and run only interstitial ad is not working

sterile tendon
#

even with AssetDatabase.Refresh() it doesn't work

    void Shift()
    {
        AssetDatabase.DeleteAsset(@"Assets\Scripts\script.txt");
        AssetDatabase.DeleteAsset(@"Assets\mp3Files");
        AssetDatabase.MoveAsset(@"C:Assets\Scripts\newscript.txt", @"Assets\Scripts\script.txt");
        AssetDatabase.MoveAsset(@"C:Assets\newMP3s", @"Assets\mp3Files");
        AssetDatabase.Refresh();
    }
dusk oyster
soft shard
# dusk oyster thanks mn, I will see the tutorial, and another question, i know that unity has...

Unity only has 2 input systems, both of them are fully functional, the "old" system that is also default and is used through the Input class, and the "new" system that uses InputActionMaps and is largely event-based (the tutorial playlist I linked covers the "new" input system) - if your trying to support multiple input devices, I would suggest the new input system is far more flexible and adaptable to more scenarios than the default "old" system, personally I would say unless you have a old project your working from, theres little reason not to use the "new" input system outside of maybe quick tests (though you can make the "new" one work for tests too)

tepid juniper
#

is it possible to create Sprite Atlas in runtime?

dusk oyster
fathom plaza
#

Hi all! I don't know if this is the right channel for this but I'm currently having errors with building my app as a .apk file. The error that shows up is as follows: ```CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Hub\Editor\2021.3.5f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2021.3.5f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-6.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"

stderr[

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':launcher:processReleaseResources'.

A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade I've tried looking up previous solutions to this but to no avail. Before this error, I was getting another error saying that android.r8isenabled = false``` is deprecated but I've already patched that up and now it's this error that shows up. Thanks in advance!

devout wigeon
#

I have the name of a static delegate and I need to subscribe/unsubscribe to the delegate. I've done this to subscribe to an event via EventInfo.AddEventHandler(). The problem is that the delegate isn't an event and FieldInfo doesn't have an AddEventHandler method. Is there a way around this? I'm new to working with reflection, so I apologize if this isn't a productive question.

thorn osprey
#

can i ask abt photon pun related stuff here

zinc tangle
#

and what about unity dashboard related errors?

#

about unity ads

tight ice
#

`void Move()
{
if (moveDirectionRaw != Vector3.zero && moveDirection != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(moveDirection); //or moveDirectionRaw
targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotDegPerSecond * Time.deltaTime);
r.MoveRotation(targetRotation);
}

    Vector3 projectedVelocity = Vector3.ProjectOnPlane(moveDirection, normalVector);
    r.velocity = projectedVelocity;


    Vector3 force = (moveDirection * speed);
    
    Vector3 anotherZeroY = new Vector3(force.x, r.velocity.y, force.z);      
    r.velocity = projectedVelocity + anotherZeroY;

   //Clamping
    Vector3 velocityH = new Vector3(r.velocity.x, 0, r.velocity.z);
    Vector3 velocityV = new Vector3(0, r.velocity.y, 0);

    if (!isFalling && stepsSinceLastJump > 20)
    {
        //r.velocity = Vector3.ClampMagnitude(velocityH, 5) + Vector3.ClampMagnitude(velocityV, clampYValue);
        r.velocity = Vector3.ClampMagnitude(velocityH, clampXZValue) + velocityV;
        this.GetComponent<Renderer>().material.color = Color.red;
    }
    else
    {
        r.velocity = Vector3.ClampMagnitude(velocityH, clampXZValue) + velocityV;
        this.GetComponent<Renderer>().material.color = Color.white;
    }


}`

Hi, how can I incorporate ProjectOnPlane into my player's velocity?
I'm trying to make it so that my player's velocity is equal to the angle of the ground beneath his feet, and THEN do the movement force calculations on top of that. But if I use the line r.velocity = projectedVelocity; , then I cannot jump.

lusty dragon
#

how should I use this line of code to slowly decrease the fill amount of an image?
I need it to decrease smoothly and I feel that Time.delta time is needed cause I need it to be consistent for every device and the editor as well.

#
void Update()
{
  waterBar.fillAmount -= 0.1f;
}
rancid kiln
main shuttle
lusty dragon
rancid kiln
#

void Update(){

main shuttle
#
waterBar.fillAmount -= 0.1f * Time.deltaTime;
lusty dragon
#

alright

#

thank you

rancid kiln
#

waterBar.fillAmount -= 0.1f*time.deltatime;

#

lol

main shuttle
#

!code

tawny elkBOT
#
Posting code

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

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

rancid kiln
#

code noice!

#

```yeeeee````

meager wasp
#

Not sure if this is more relevant to #💻┃code-beginner or this channel so i'll just ask here. Right now i have a class that does some work and uses an async operation to do it's work. In another class i need to wait until the async operation of class 1 is done before i can access the variables. I'm not quite sure what the correct thing to use for this is. I tried having a look at observer patterns but they don't seem like the easiest solution. Is there some easy way i am missing or is it just implementing observer patterns?

alpine jasper
# meager wasp Not sure if this is more relevant to <#497874004401586176> or this channel so i'...

Depends on relationship between your Worker and Observer. If Observer controls the worker I'd go like this:
In Worker:

public async Task DoWork() { .... }

in Observer:

await worker.DoWork()

However if Observer merely observes the worker, I'd go with an event.

In Worker:

event Action WorkDone; public async void DoWork() { .... WorkDone?.Invoke(); }

in Observer:

worker.WorkDone += OnWorkDone;

thin aurora
#

Depending on what the specifics of this operation is, this field will be named differently, of course. When true, continue the Update and invoke some method that needs to happen afterwards.

tawny elkBOT
#
Posting code

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

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

thin aurora
thin aurora
#

Then you need to apply that to the main async task invoker, which is messy and it would mean that there is always a set number of tasks, instead of it being more dynamic

#

Just being able to call the task, storing the task in memory, and waiting in a seperate update method until its state is completed, which is what I suggested, does not create any more code than is necessary, and does not force you to wait for multiple tasks.

alpine jasper
#

Well, we don't really know in detail what the OPs situation is, all of these methods might fit

#

we don't even know if he works with MonoBehs to be able to use Update 🙂

thin aurora
#

I'm gonna take a wild guess and say that any question in a channel about Unity code, in a Unity server, is about Unity 😉

#

The question is what type of async operation he is using, hence why I can't give a broad answer on what the operation can return, nor if it is possible to wait for any type of event

alpine jasper
meager wasp
#

sorry was trying to implement the suggestion from dive let me try to give some more information. Right now working with MonoBehaviours currently the "worker" is using

 AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale); // create async load of localisation table
``` to get the localization table of unity and then setting up some data the "observer" needs to access
thin aurora
#

Then whatever needs to await it get this, checks if it's not null, and then checks if AsyncOperationHandle has been completed using whatever field defines it in there

#

If everything passed, you are done waiting and can respond it ot

thin aurora
meager wasp
#

i'm currently using

Localisation.Completed += Handle_Completed;
``` to wait until the operation is completed in the localisation class. and after that handle is done i want to invoke tha "observer"
#

i can't realy observer the async operation as that might mean the data is actually not yet available to access from the observer (as it is doing something with the table)

south violet
#

Hello, anyone knows a good approach to check object percentage visibility by camera every frame? Like it is for covered by another object and I can see only a part of it and I would like to know how much of it is visible in current state. This would be for the situation where camera moves and rotates as well as the objects are moving and rotating

trim spoke
#

Hey Guys! Does anyone has experience with encrypting scripts locally to prevent cheat engines?

alpine jasper
thin aurora
#

Never, ever use async void. Properly await a Task, and handle on the result, even if it returns nothing.

#

This is why I used an Update method

alpine jasper
thin aurora
#

Then it's still a fire and forget method, and any errors are lost since you did not properly await the Task

#

There is a very specific reason why I suggest an Update method, you know

alpine jasper
thin aurora
#

Adding a try-catch block is going to suppress the error, and you are unable to handle any errors whilst waiting for the task to finish. Once again totally avoidable if you just wait for a result in an Update method.

alpine jasper
thin aurora
#

There's literally no priority with this. A fire-and-forget method is going to crash your application one way or another if you do not properly await the result of the Task

#

I'll type it again, this is why I used an Update method. You wait for the result, and you properly retrieve the result, allowing exceptions to be thrown

#

It's not about whether or not your code looks cleaner if you do it another way, your example will literally crash the application as soon as something go wrong. Not to mention there is a big chance the stacktrace might not be informative

#

Note the "It's ALWAYS bad" part.

alpine jasper
thin aurora
# alpine jasper this can get messy though. if you have to wait for multiple entities your Update...

You already gave a solution for this some messages above. You can use Task.WhenAll.
And like I said before, it's not about whether or not your code looks cleaner if you do it another way
Your application will be broken with edge cases if you don't do this
And if I can't convince you what the problem is, so be it. But don't spread misinformation and give some bad solution when it comes to async code. It's a tough subject, and it's very important you handle async code properly, to avoid sync-over-async code/deadlocks/memory issues/crashes/whatever.

desert shard
#

I have a material set to Transparent -> Premultiply, How does one fade it out ? I've noticed I have to set emission to zero and colour alpha to 0 for it to be transparent, surely theres a simpler way?

alpine jasper
# thin aurora Here are some best practices about the async-await pattern. I think the Async vo...

thx I'll take a look, though what stands out to me is that this ting is ASP.NET manual. This worries me because I know that async/await in Unity works quite differently than in regular C#.
I'm not opposed to having more reliability checks per se, but I'm opposed to doing that in an Update. I suspect this is not very scalable and not really universal, since having an update method requires using a monobeh, which is best avoided for the core game code. (sure there are alternatives like implementing ITickable from Zenject, but do we really need to resort to this?)

#

Tell me how this will break, I'm curious

private async void LoadLocalisation()
{
    AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);

    try
    {
        await Localisation.Task;
    }
    catch (Exception e)
    {
        Debug.LogError(e.Message);
    }

    LocalisationLoaded?.invoke()
}```
thin aurora
thin aurora
#

Now classes are forced to still invoke behaviour when LocalisationLoaded is invoked, even though the task failed, and it is unknown whether or not the localisation truly finished succesfully

#

Solution: Another event that is invoked should an error happen, but now you have to create yet another method that handles any errors

#

Another problem: What if a class needs to know if localisation was initialized at a later stage? The event might have already been invoked at that point. You can then once again check the Task if it completed using an Update method 🙃 .

alpine jasper
#

Let's goo

event Action<bool> LocalisationLoadingFinished;

private async void LoadLocalisation()
{
    AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);

    try
    {
        await Localisation.Task;
    }
    catch (Exception e)
    {
        Debug.LogError(e.Message);
        LocalisationLoadingFinished?.Invoke(false);
        return
    }

    LocalisationLoadingFinished?.Invoke(true);
}
thin aurora
#

Do I need to do this with every single async method I create? What If I want to ensure they all finish before I invoke my own behaviour?

alpine jasper
#

if we only want to load localisation once and provide to anyone at later stages, this might work.

private event Action<StringTable> LocalisationLoadingFinished;
private StringTable localisationResult;

public void AddLocalisationLoadedHandler(Action<StringTable> handler)
{
    if (localisationResult != null)
    {
        handler(localisationResult);
        return;
    }

    LocalisationLoadingFinished += handler;
}

private async void LoadLocalisation()
{
    AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);

    var success = true;
    try
    {
        await Localisation.Task;
    }
    catch (Exception e)
    {
        Debug.LogError(e.Message);
        success = false;
        return
    }

    if (success)
        localisationResult = Localisation.Result;
    
    LocalisationLoadingFinished?.Invoke(localisationResult);
    LocalisationLoadingFinished = null;
}
alpine jasper
thin aurora
# alpine jasper if we only want to load localisation once and provide to anyone at later stages,...

See where this is going? More and more edge cases to handle, even though this method has one simple task: loading localisation.

// Inside your service
private Task _localisationTask;
public LocalisationTask => this._localisationTask ??= LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);


// In your monobehaviour
[SerializeField] private whatever _localisationService;
private bool _localisationBehaviourFinished;

void Update()
{
  if (this._localisationBehaviourFinished || this._localisationService.LocalisationTask.IsCompleted)
  {
    return;
  }
  this._localisationBehaviourFinished = true;

  // Localisation was loaded.
}
#

And all of that because you're actively trying to avoid just using a Task and the Update method as a listener

thin aurora
#

So just stick with the wheel that was made for you. Don't cut corners because you think the code does not need it. It's a perfect recipe for disaster and you will most definitely shoot yourself in the foot later on.

alpine jasper
thin aurora
#

Why would ITickable be any better than an Update method?

#

And why would I need to download a whole package for something Unity already has?

#

And why are you suddenly agreeing with my method? RisitasLaugh

alpine jasper
thin aurora
#

So your point is that Zenject allows regular classes to have a method that is invoked every tick, or something?

alpine jasper
thin aurora
#

That's good to hear, call it very surprising to see the switch this sudden 🙃

alpine jasper
#

well, you clearly wrote a code that is shorter than mine which does the same thing as reliably.
As long as this class does not do much else I'd say this is good.

alpine jasper
#

monobehaviour is just generally a BIG freaking entity on it's own, even if you did not add anything to it. It has it's own lifecycle, it can't be spawned with new() (well, it can, but it's best avoided) etc.. As someone who was once tasked with covering a legacy project with unit tests let me tell you: this is NOT fun.
Better keep your entities as simple as possible. If this thing aint need to be a monobeh - don't make it one

#

unless you're participating in a game jam or the whole scope of your project is like 1 month - then you can do whatever you want 😄

tiny stirrup
#

Anyone have any thoughts on whether this is an alright way to call mouse collider events on another object which lacks a collider? is sending generic messages risky in any way?

dusky lake
#

If you are unsure about unexpected behaviour you could put a custom monobehaviour on all of those objects and call a custom function that does what you want it to do, if you want different ones and need a list of them create a common interface and implement that on each

woven matrix
#

need help figuring why my camera position changes if I change bethewn these two types of code:
code that generates the left

    if(Physics.Raycast(ray,out raycastHit, 999f,aimColliderMask)){
        aimTransform.position=raycastHit.point;

code that generates the right :

aimTransform.position=ray.direction*100f;

dont understand why this happens, can any one help? the acamera gest angled on the right

tiny stirrup
tiny stirrup
tiny stirrup
#

could you post a picture of a bigger snippet of the code?

#

Maybe when you gnerate the ray?

woven matrix
#

'cs
void ManageCamera(){

    screenCenterPoint = new Vector2(Screen.width/2f, Screen.height/2f);

    Ray ray = Camera.main.ScreenPointToRay(screenCenterPoint);
    
    ////seccond option aimTransform.position=ray.direction*100f;

  /////first option
    if(Physics.Raycast(ray,out raycastHit, 999f,aimColliderMask)){
        aimTransform.position=raycastHit.point;
    }

////////
rotatePlayerToAim();

    if(starterAssetsInputs.sprint)return;          

    if(starterAssetsInputs.aim){
        aimVirtualCamera.gameObject.SetActive(true);
        mouseControls.SetSensitivity(aimSensitivity);

       return;
    }
    aimVirtualCamera.gameObject.SetActive(false);
    mouseControls.SetSensitivity(normalSensitivity);

}

void rotatePlayerToAim(){
    
    Vector3 worldAimTarget = aimTransform.position;
    worldAimTarget.y =mouseControls.mouseTransform.position.y;
    Vector3 aimDirection = (worldAimTarget - mouseControls.mouseTransform.position).normalized;
    mouseControls.mouseTransform.forward=Vector3.Lerp(mouseControls.mouseTransform.forward,aimDirection,Time.deltaTime*20f);   
}

'

tiny stirrup
#

what is the aimcollider placed on?

woven matrix
#

default

tiny stirrup
#

Sorry I meant the aimtransform?

#

is that on the player?

woven matrix
#

the player and the aimtranform are child of a root parent

#

the player is the "ratplayer" the aim transform is the "aimlookattransformPosition"

tiny stirrup
#

maybe start by trying to make both rays the same distance

woven matrix
#

ok

tiny stirrup
#

so either 999f or 100f.

#

Its hard to tell without having the whole thing in my hands(though I might be missing something, pretty hung over^^)

woven matrix
#

dont worrie thanks

#

ok I made it 999f and it got corrected the angle

#

ok I think I understand why

#

as the camera is tilted from the player, for the angle to "disapear" it neets to be far enought for it to not be unoticable

#

so I guess a better way to resolve this is not to use the camera as the starting point but the character

#

but no, the camera is the player view

#

ok but its corecter either way thanks man

#

well

#

its not corrected

#

xD the shot still misses the aim point a bit

tiny stirrup
#

try changing the distance to 'Mathf.Infinity'

woven matrix
#

I am gona try to use a emty transform that is faraway from the camera

#

and use it as the aim

#

but then will do infinit

#

if it does not work

tiny stirrup
#

cool

#

gl gl homie

woven matrix
#

ah no I need those transforms because there will be multiple multipleyrs rats and I need each ones controll each mouse

#

ok gona use that

#

Mathf.Infinity works man

#

but I gett allot of these
'transform.position assign attempt for 'AimLookAtTransformPosition' is not valid. Input position is { -Infinity, Infinity, -Infinity }.'

#

ah its because I am trying to get the transform, and not just use it as math prob

ripe vale
#

What is normally used / more recommended ? Using a character controller and calling the move function and allowing it to handle collision etc, or using transform.position to move your character and handle collision using raycasts ?

dusky lake
dusky lake
#

MovePosition

#

sorry

vestal geode
# dusky lake MovePosition

MovePosition ignores physics same as Rigidbody.position, but it's visually smoother due to interpolation

dusky lake
#

Uh if i'm not mistaken it takes physics into account

#

like you cant MovePosition through a wall

vestal geode
ripe vale
vestal geode
thick socket
#
public event Action<Collectible> OnPickup;

so the "type" of the action is just all the arguements that the OnPickup needs to have and anything that += the event needs also?

#
public event Action<string, string, string> OnPickup;

so I would just need to pass in 3 strings when invoking OnPickup here and the += needs to take 3 strings?

simple egret
#

Yes

thick socket
#

thanks!

simple egret
#

In fact if you ctrl+click the Action you'll see its declaration

thick socket
#

sweet thanks!

simple egret
#

delegate void Action<T>(T arg1); -- accepts methods that return void and take an argument of type T

thick socket
#

is it better to do something like this typically?

GameManager.instance.playerInventory.Equip(tmpStore.item, isBaseHero);

or create an event with the 2 types that Equip has and have the playerInventory sub to event?

#

not sure when to call functions in other classes vs use events

simple egret
#

Use events when the target of the call is not known beforehand

thick socket
simple egret
#

The player died
Alright, but who can "reference" that? It's not known beforehand. You would use an event here

thick socket
#

that makes sense thanks!

#

wont I need to know who can reference it since I will need to put in a sub to the event?

simple egret
#

An enemy would subscribe to it, so it cheers your death. Or not.
The UI could subscribe to that to display a death screen. Or not.
etc.

thick socket
#

ah, so if a bunch of things need to know about it

#

events are good

simple egret
#

You only need to know where the event is

#

It's like reversed

#

The sender notifies, and receivers are free to read it or not

thick socket
#

so if I have a bunch of different places that I can equip armor to player, they should just call the "player.redoStats()" instead of make events

#

since I already know only the player needs to know it

simple egret
#

Yeah just a simple method call will do here.

thick socket
#
private void OnCollisionEnter2D(Collision2D collision)
    {
        var tag = collision.gameObject.tag;
    }```
#

should I be using .gameObject or .transform here?

leaden ice
thick socket
#

for some reason when using OnTriggerEnter2D you can just do collision.tag...not sure why its different for OnCollisionEnter2D

#

¯_(ツ)_/¯

leaden ice
#

look at the parameter type

#

look up that type in the documentation

#

think about what it is

thick socket
leaden ice
#

they don't

#

that's why I'm saying, pay attention to the parameter type

rain minnow
thick socket
rain minnow
hasty haven
#

Made use of a nested ternary for the first time lol

// Set color to white when mouse over, otherwise show selected or default color
nameText.color = isMouseOver ? Color.white : isSelected ? tabGroup.ButtonColorSelected : tabGroup.ButtonColorDefault;
#

The actual code lerps the color but this is the condensed version

rain minnow
#

eww . . .

hasty haven
#

not really a fan of evaluating the same expression multiple times with if/else and did this since the script is very short and easy to read

leaden ice
thick socket
#
protected override void Start()
    {
        base.Start();
        hpText = GetComponentInChildren<TextMeshProUGUI>();
        maxJumps = 2;
        Shoot();
    }
#
NullReferenceException: Object reference not set to an instance of an object
#

Its saying my hpText is null

#

Im not sure why as it was working earlier and afaik I haven't touched this part of code

leaden ice
#

because that line with hpText = GetComponentInChildren cannot throw this error

thick socket
#
NullReferenceException: Object reference not set to an instance of an object
Player.HpGUI () (at Assets/Scripts/sprites/Player.cs:108)
Fighter.Start () (at Assets/Scripts/sprites/Fighter.cs:76)
Player.Start () (at Assets/Scripts/sprites/Player.cs:23)
thick socket
#
    {
        base.HpGUI();
        if (hpText == null)
        {
            Debug.Log("hptext is null");
        }
        hpText.text = hitpoint.ToString(); //line 108

    }```
leaden ice
#

which line?

thick socket
#

the one that says //line 108 next to it 🙂

#

aka the last one

leaden ice
#

oh sorry missed that

thick socket
#

all good lol

#

the debug.log is printing

#

so ik hpText is null

#

but I don't know how its null

leaden ice
#

this is happening Start

#

is HPGui running inside base.Start?

#

because that's being called BEFORE you assign hpText

thick socket
#

yeah, fighter has this in start()

#
protected virtual void Start()
    {
        character.Animator.SetInteger("WeaponType", (int)WeaponType.Melee1H);
        _rb = GetComponent<Rigidbody2D>();
        myCollider = GetComponent<Collider2D>();
        hpSlider = transform.GetComponentInChildren<Slider>();
        stats = new();
        target = FindTarget();
        pauseShooting = true;
        HpGUI();
    }
 protected virtual void HpGUI()
    {
        hpSlider.value = (float)hitpoint / maxHitpoint;
    }
#

I can throw a

        hpText = GetComponentInChildren<TextMeshProUGUI>();

as a conditional inside of the override HPGUI()?

#

feels like bad coding to have to do it that way however

#

oh, I just had to call my hpText = GetComponentInChildren<TextMeshProUGUI>(); before base.start()...thanks @leaden ice 🙂

ancient cloak
#

does anybody use odin in their studio?

#

i'm looking at pricing, and the enterprise package is on the pricy side, but i noticed that it includes support and access to devs. if i don't care about that, can i get the asset store inspector/validator? or do i need an enterprise license

#

not a code question but it's a coding tool. feel free to tell me if i need to move it

thick socket
leaden ice
#

over 200K means you need enterprise

thick socket
#

I would suggest you try it out as its free

ancient cloak
#

@leaden ice right i saw their pricing but it also includes superfluous things (to me)

leaden ice
ancient cloak
#

whereas i can just buy this

leaden ice
#

You could but you'd probably be in violation of their license agreement

#

¯_(ツ)_/¯

#

whether you are worried about that is up to you

late lion
ancient cloak
#

oh i see the asset store pricing is simply their personal license

sterile tendon
#

I have a weird situation

#

I have old text to speech mp3s for a scene and new ones get cycled in once the scene ends

#

right now I just delete the mp3files folder and rename newMP3s to mp3files

#

but for some reason every time it does that unity does this

#

is there any way to override this message?

#

other than that all the assets end up in the right place

leaden ice
#

I'd guess this happens if you're using the System.IO stuff directly instead of handling things properly with AssetDatabase

sterile tendon
#

oh I'm using an external python script for it

#

for some reason assetDatabase doesn't work at all

leaden ice
#

yeah - you'll have to handle the meta files yourself or use AssetDatabase

sterile tendon
#

weird I thought the .meta files would be unnaffected since I'm just renamaing the newMP3s folder

#

oh maybe they don't have time to generate at all

#

my script just checks if the mp3s are all generated and then immediately changes the folder name

sterile tendon
#
    void Shift()
    {
        //for folders
        AssetDatabase.DeleteAsset(@"C:\Users\Cameron\watchmealways\Assets\mp3Files");
        AssetDatabase.MoveAsset(@"C:\Users\Cameron\watchmealways\Assets\newMP3s", @"C:\Users\Cameron\watchmealways\Assets\mp3Files");
        AssetDatabase.Refresh();
        //does the script, commented out for testing
        //System.Diagnostics.Process.Start("CMD.exe", "/C py \"C:\\Users\\Cameron\\watchmealways\\Assets\\Scripts\\shift.py\"");
        //debug: py "C:\Users\Cameron\watchmealways\Assets\Scripts\shift.py"
    }
leaden ice
sterile tendon
#

oh right sorry

leaden ice
#

didn't we have that discussion yesterday haha

#

I'm having deja vu

sterile tendon
#

yeah I just remembered lmao

leaden ice
#

I even remember Cameron

sterile tendon
#

jesus I've been working on this thing for way too long

#

forgetting the most basic shit

leaden ice
#

take a break Cameron

sterile tendon
#

at least it generates new breaking bad episodes +text to speech completely automatically now

#

plus the rate controller works

sterile tendon
sterile tendon
#

I fixed it and everything works except for moveAsset()?

#

idk why

#

this is the last thing I have to fix and then the project should be fully functional

#

doesn't even throw an error, it just doesn't rename the folder

swift falcon
#

So I'm making a game and I just started with networking
I have world generation, and I am worried that if the player enters a world he will see clients in other worlds instead of the same world he's in.

I am using the Netcode package & Multiplayer Tools package
How would I go about making it so I could only see people in the same world??

tight ice
# rancid kiln are you trying to like walk up slopes or something?

well, I ran into an issue where my jump works how I want it to work on flat ground, but once I am on an upward slope while moving forward the jump turns into basically nothing
i theorize that it's because i'm running into the slope instead of along with it so my upwards force of the jump gets 'canceled'

#

but i am not sure how to edit the code to make it respect the angle of a slope beneath character's feet while moving forward and jumping

sacred shuttle
#

hello, well I want my character to hold the weapon ( even when switching to a new one etc like in cs go), how should I do it? should I use animation rigging etc?

rancid kiln
hexed geode
#
void Start()
    {
        foreach (SpawnInstruction instruction in spawnInstructions)
        {
            GameObject spawnedObject = Instantiate(basicObject, instruction.startPosition, Quaternion.Euler(instruction.startRotation));
            spawnedObject.transform.localScale = instruction.startScale;
            SpriteRenderer renderer = spawnedObject.GetComponent<SpriteRenderer>();
            renderer.sprite = instruction.sprite;
            renderer.color = instruction.color;
            AppearTimed timedScript = spawnedObject.AddComponent<AppearTimed>();
            timedScript.appearTime = instruction.appearTime;
            timedScript.disappearTime = instruction.lifeTime;
            timedScript.telegraphStart = instruction.telegraphAppearStart;
            timedScript.telegraphEnd = instruction.telegraphAppearEnd;
            timedScript.telegraphAlpha = instruction.telegraphAlpha;
            Rotating rotating = spawnedObject.AddComponent<Rotating>();
            rotating.rotationSpeed = instruction.rotationSpeed;
            rotating.rotationAcceleration = instruction.rotationAcceleration;
            FollowPlayer followPlayer = spawnedObject.AddComponent<FollowPlayer>();
            followPlayer.followPlayer = instruction.followPlayer;
            followPlayer.minOffset = instruction.minOffset;
            followPlayer.maxOffset = instruction.maxOffset;
            followPlayer.maxRandomRotation = instruction.maxRandomRotation;
        }
    }

this isn't a good way to do this right

#

this is supposed to be done to >50 objects at the start of the scene

cunning igloo
thick socket
#

this is the closest I've found

#

is the best thing to just sort anytime if I need to do that?

brisk marsh
#

What are the risks of a dynamic-get, dynamic-set property if you're handling all of the compatible types and refusing incompatible types? [This is not in game-ready code, it's for an editor window (and some static classes for the future)]

leaden ice
#

are you talking about the dynamic keyword?

brisk marsh
#

yeah

#

@leaden ice

leaden ice
#

Isn't this just a SerializedProperty ?

#

and couldn't you just use object and casting?

brisk marsh
#

Can't use an object and casting

#

can't genericize (the typical way)

#

I'm filtering all of the serializedproperty types (for a generic wrapper) and creating a simplified accessor for the serialized property's property type.

#

I'm already aware of what that entails if I were to not restrict the value types accepted* at all (toolkit users will find crashes and instability from incompatible types)

normal arch
#

im struggling to find tutorials that allow jumping in a top down 2d game; all of them are either for gamemaker, don't have exactly what i need or don't actually tell me how to do it when if they have the perfect thing for me. Does anyone know how i could implement this into my game, if so thanks, because this would really boost my motivation to continue with this game

leaden ice
#

jumping in a top down game seems weird

normal arch
#

yeah it's like platforming

#

if you've ever seen or played the game crosscode, you'd understand what i want

#

i get that it's uncommon

leaden ice
#

you'd have to have some concept of "depth"

brisk marsh
#

Praetor, do you have any advice around the keyword dynamic

normal arch
#

yeah a lot of the tutorials say that but the only unity tutorial i found isn't for platforming

brisk marsh
#

it's a very oddly documented one where people are either "never use it" or "only use it with specific libraries"

leaden ice
brisk marsh
#

Yeah that's a big issue

leaden ice
#

I also just avoid it like the plague because the whole point of having a nice statically typed language is static types. dynamic gives me nam flashbacks from my dayjob where I have to write Python

brisk marsh
#

I'm using it right now as part of a framework I'm working on for Unity Editor Windows that works like a simplified overlay so other programmers in my university and course can get into the UIElements toolkit without a lot of the hassle of long (and sometimes hard to read) lines for accessing helpful powerful elements.

#

But, yeah, it's hard to say if it's viable. I've tested it and it's working fine - just would feel comfortable knowing all the risks.

#

It should not (and should never) compile with the rest of the Unity game* code because it's in a folder in assets labelled Editor, so I don't believe IL2CPP or Mono would have to compile it

leaden ice
#

the camera shape is based on the game resolution shape

#

change your game resolution (game view) and it will change the camera shape

#

because it's rendering to a render texture, right?

#

That camera's shape is based on the render texture's shape

thick socket
severe maple
#

in unknown territory here, so please point out if im heading in the right direction. I'm trying to detect how lit the player is, like with the old Thief games. my fps player 'model' is a upside down cone with a 2nd ortho camera called LightCheck just above his head, looking down, with basically just the model in shot. He is this shape so the camera can detect light sources affecting the player from all around. This camera outputs to a render texture of 1x1, and i getpixel color of this to find the overall color of the player, taking in light sources. That's where Im at so far, i figure i can use this color to check if the player is in shadow

leaden ice
#

field of view is a property on the camera

#

actually you're using orthographic

#

so you'd change the camera's Size to zoom in/out

thick socket
devout solstice
#

Say I want to assign a component to a variable and edit the component through the variable, I've noticed setting it to a component variable, it doesn't let me edit it, is there anyway I could do this?

hexed oak
#

are you talking about Component?

lucid valley
#

show some code?

devout solstice
#

So say I have a component Jim right, like a script

lucid valley
#

like as asked above are you using Component as the variable type?

devout solstice
#

This is hypothetical because I've tried it before, and it didn't seem to work so I don't use it as such I don't have any code

#

But yes

lucid valley
#

public class JimComponentMono : Monobehaviour
{
    public void DoThingJim()
}

//In other class
Component JimComponent;

private void DoThing()
{
    //This wont work no
    JimComponent.DoThingJim();
}
devout solstice
#

Ok

lucid valley
#

you'd either have to cast it (since JimComponentMono is derived from Monobehaviour which is derived from Component)

#
public class JimComponentMono : Monobehaviour
{
    public void DoThingJim()
}

//In other class
Component jimComponent;

private void DoThing()
{
    var jimComponentMono = jimComponent as JimComponentMono;

    //This works
    jimComponentMono.DoThingJim();
}
#

or use the actual type (preferred way, also lets you set the Monobehaviour in the inspector if serialized)

#
public class JimComponentMono : Monobehaviour
{
    public void DoThingJim()
}

//In other class
JimComponentMono jimComponent;

private void DoThing()
{
    //This works
    jimComponent.DoThingJim();
}
devout solstice
#

ok so I could have Jim JimVariable;

lucid valley
#

yeah, that is the way to do it

devout solstice
#

I see I've done that before, ig it just never clicked in my brain

#

Thanks for the help

ancient cloak
#

does anyone know how in odin i could have say, a boxgroup with a checkbox inside the title that if checked will expand the content of the boxgroup? sec i have an image tha'ts close

#

i'd like the checkbox to be inline with the word "position" though, preferably IN the boxgroup title

#
[BoxGroup("Position")] 
[HideLabel] 
[HorizontalGroup("Pos")] 
[SerializeField] 
private bool _tweenPosition;

[BoxGroup("Position")]
[HideLabel]
[HorizontalGroup("Pos")]
[ShowIf("$_tweenPosition")]
[SerializeField]
private FromToPair<Vector3> _position;
#

oh togglegroup. thanks chat

devout solstice
#

could I get the gameobject through addlistener?

leaden ice
devout solstice
#

A button

#

On a script

leaden ice
#

wdym "get the gameobject"? Which gameobject do you want to get and where?

devout solstice
#

Im gonna have multiple buttons and don't want to have to add this script to each one, so I'd prefer to have it go through a list of the buttons and add a listener to each one and if one is clicked it gets which button it was that was clicked

swift falcon
#

Is there any event that is called when an object or its parent is set active?
Something like

void OnActivate(){}```

And if not, is there an easy way to do the same idea manually?

The only idea I can think of is storing Time.time in a float every update and if X seconds has passed since the time was last stored then call OnActivate()
Anything better?
Performance is really important here
swift falcon
#

Oh yeah thanks, should have thought of that lol

#

Is there any way to make this more performant?

GameObject tile = Instantiate(preset.TileGO, point, Quaternion.identity);

Tile tileScript = tile.GetComponent<Tile>();
...```

I have to instantiate a lot of gameobjects and its causing lag spikes whenever a new chunk is generated so I'm looking for ways to fix that
leaden ice
#

use direct Tile references

#

but in general, your problem runs deeper than that - use the profiler to see what's slow about spawning your chunks

#

you might need to reduce or eliminate Awake/OnEnable/Start code in those chunks, or make smaller chunks for example

swift falcon
#

Are you saying to do something like this?

Tile tile = Instantiate(preset.TileGO, point, Quaternion.identity);```
I get an error, or are you just saying to cut out the assignment to tile?
leaden ice
#

not TileGO

#

and the type of that field should be Tile

#

not GameObject

#

Then you can write:
Tile tile = Instantiate(preset.tilePrefab, point, Quaternion.identity);

swift falcon
#

Alright that worked thanks. Not sure how all the information about the prefab is being stored in a Component variable though that's interesting

#

I'll see if I can cut out any Starts, Awakes, etc

leaden ice
#

to make sure that's actually an issue

tall lagoon
#

Hey guys im having an issue in unity currently where i have a fishing level with a fishinging spawner that spawns fishes at the start but then i have a button in the corner to go to next scene which is the shop. Once I entered the shop and then come back to the fishing level i want the script to replay again so another batch of fish spawn since currently when i go to the shop, and come back to the fishing level there's no fish. Here's fish spawner script https://gdl.space/kihayakepu.cs.

leaden ice
#

then unload the shop scene when I'm done

tall lagoon
#

wdym?

leaden ice
#

and the normal fishing scene will still be there, waiting, with all the fish unchanged

#

you can load scenes additively

tall lagoon
#

no idont want the fish unchaged

leaden ice
#

i.e. load a new scene and keep the old one around

tall lagoon
#

iwant the script to like replay get what imsaying?

#

like do it once

leaden ice
tall lagoon
#

no thats for

#

so ican acsees it in the other scenes

leaden ice
#
    private void Awake()
    {
        if(instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
            
        }
        else
        {
            Destroy(gameObject);
        }
    }```
Get rid of everything in here except for the `instance = this;`
tall lagoon
#

so i can add more types of fishes to un;pc

#

iok

leaden ice
#

You need to do this somewhere else besides Start then:

    void Start()
    {
       
            for (int i = 0; i < FishesToSpawn; i++)
            {

                SpawnFishes();
            }
        
       
    }```
#

you should instead make a function like:

    public void InitializeFish()
    {
            for (int i = 0; i < FishesToSpawn; i++)
            {
                SpawnFishes();
            }
    }```
#

then have another regular scirpt in the scene that does like:

void OnEnable() {
  FishSpawner.Instance.InitializeFish();
}```
tall lagoon
#

o ok

#

thanks

#

and wait

#

how can icheck if the scene is loaded so it only plays once

lone lynx
#

Where do i go if im looking to help someone with a project

thick socket
lone lynx
#

Like art or music

thick socket
lone lynx
#

I wanna do an art collab?

#

or a music colab if someone needs game music

leaden ice
thick socket
#

wrong discord lol

leaden ice
#

why would you want to do this

#

that was the whole point of your question

swift falcon
#

So here's what I'm looking at in my profiler:
(Separated into the levels)

TileMap.Update() = 92.75ms

Transform.SetParent = 12.82ms
Instantiate = 72.2ms accumulated time
GameObject.Deactivate = 4ms accumulated time

Transform.SetHierarchyCapacity = 10.66ms
Instantiate.Copy = 31.75ms accumulated time
Instantiate.Produce = 24.35 accumulated time
Instantiate.Awake = 15.66ms acccumulated time

The rest seems pretty miniscule
This all happens over a single frame and then goes back to normal
Which of these do I need to focus on?

leaden ice
#

The biggest ones first basically

whole parrot
#

Which channel is for shaders?

#

It's code, but its with shaders

swift falcon
#

Ok I think I solved it by turning the GenerateMap() method into a coroutine and now it only generates 1 tile per frame
Since the chunks are generated just outside the camera this works perfectly!
(Unless I realise something in a few days and have to change all this back lol)

void basalt
#

Asked this a while ago and didn't really get an answer so here we go again:
I'm basically looking to grab a bunch of data out of an animator. Things like current animations playing, blend ratios, etc.

After I get that data, I need to be able to send it over a network, and recreate that pose exactly on a separate machine

#

is this at all possible? I've googled so much and I just can't find anything about doing this

#

It seems that I'm able to get the animator state info and the blend weights and such, I just can't find anything on actually reconstructing it

ancient cloak
#

is there a command for the xy problem yet

#

!xy

#

try to explain the problem you're trying to solve, not the hiccup you hit in your attempted solution, might make things more clear

void basalt
#

pretty important

stable rivet
visual flare
#

you know you've used unity for too many years when you shrug off domain reload crash 😅

void basalt
#

Client must tell the server somehow what animations he's seeing other players at, at the time of his bullet shot (or whatever)

stable rivet
# void basalt Wrong. Client tells the server which snapshot states he's looking at, as well as...

Well, seems like you're very familiar with what you want to be doing. All I will say is what you are trying to do with the animator is a huge pain, if not flat out impossible. If I were in your shoes, I would be looking for a different approach entirely, and maybe not be allowing the client to tell the server whether or not their animation has seen a hitbox connect (or whatever you're implying by "what animations he's seeing other players at, at the time of his bullet shot")

void basalt
#

Client doesn't call the shots, he only tells the server what server-confirmed states he's looking at

stable rivet
#

I'm no networking expert, just know enough about the animator to know as soon as you're treading in state info land, a new approach is needed

void basalt
#

I've been looking for a solution so long and the animator docs are just so poorly written on this topic

harsh lintel
#

Idk what other channel I would put this in but hey y’all I’m having an issue regarding the Animation Rigging package. I’m setting up an IK fps character but when I build the rig and move an object containing the gun and the arm IK targets inside, the arms don’t move with the targets.

The only way I can get it to work is by having the arm joints inside the moving part too

So instead of it being real where the hands will jolt back from recoil and the shoulders stay put, either I have to put the entire arm structure inside the gun so the entire arm and shoulders move with the gun (which is ugly and defeats the purpose of IK) or the arms don’t move even tho their IK targets are moving

#

How would I fix this?

#

Btw the arms move with the targets if you move the targets themselves directly but if you move the parent of those targets, they wont move

swift falcon
#

and if I scale the parent the position is wrong but they line up

#

nvm just had to match the pivot with the offset of the hitbox

#

im slow

amber haven
#
public class MonitorScreen : MonoBehaviour
{
    public Camera MonitorCamera;
    public GameObject Screen;
    private RenderTexture ScreenInput;
    private Material ScreenOutput;
    private Material ScreenOff;

    void Start()
    {
        MonitorCamera.enabled = true;

        ScreenOff = Screen.GetComponent<Renderer>().material;
        Screen.GetComponent<Renderer>().material = new Material(Shader.Find("Standard"));

        ScreenInput = new RenderTexture(1600, 900, 0, RenderTextureFormat.Default);
        ScreenInput.Create();
        MonitorCamera.targetTexture = ScreenInput;

        Screen.GetComponent<Renderer>().material.mainTexture = ScreenInput;
    }
}

This is my script for rendering a cameras output onto a plane but when it is rendered, it appears flipped vertically, how do I fix this?

dusky lake
#

Are you sure that it isnt just your plane being flipped?

amber haven
halcyon gyro
#

so, im making a 2d platformer and my player movement is constantly fighting against the rigidbody2d ill send code

#

lemme open up my unity again

#

im slightly new to coding and im still doing someme learning and dont know exactly how to use if () statements which im assuming i would have to use but here just take a look

#

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

public class PlayerController : MonoBehaviour
//variables to control movement
{ public float horizontalInput;
public float speed = 10.0f;
//vertical allignment
public GameObject Player;
//jump variables
public float verticalInput;
public float jumpPower = 100.0f;

void Start()
{

`` }

void Update()
{ 
   {//movement script
   horizontalInput = Input.GetAxis("Horizontal");


    transform.Translate(Vector2.right * Time.deltaTime * horizontalInput * speed);
    //player allignment
    Player.transform.eulerAngles = new Vector3(Player.transform.eulerAngles.x, Player.transform.eulerAngles.y, 0f);
   } 
   
   {//jump script
   verticalInput = Input.GetAxis("Vertical");

   transform.Translate(Vector2.up * Time.deltaTime * verticalInput * jumpPower);
   }
}

}``

#

also have no idea how to make it to where i can jump w/ my spacebar

#

now that i think of it i should've put this in beginner coding help

#

@here

halcyon gyro
#

lol same here man

#

imma put this in begginer coding

cosmic rain
still ruin
#

I'm trying to make some code that I can use to adjust the values of the suspension spring force and damping force from a published build.
I can read the values for spring force and damping force but I cannot set them.
Does anyone know how I can set the values?

#

The coding hover menu thing suggests that the wheelcollider.suspension.spring is capable of both {get ;set; }

whole parrot
#

I never knew CubeMaps could be so annoying in script

whole parrot
still ruin
#

first error is CS1955: Non-invocable member 'Join.Spring.spring' cannot be used like a method
Second and third errors are CS1612: Cannot modify the return value of 'WheelCollider.suspensionSpring' because it is not a variable

buoyant crane
#

the first one makes sense, but i’m trying to find in the documentation what the it returns

vagrant blade
keen eagle
#

is it possible to have 5 inch diameter circle sprite on any resolution or device

buoyant crane
still ruin
#

correct

#

harvester is the parent game object of the wheel colliders

whole parrot
still ruin
#

and vehicle controller is the script that controls the torque and rotational angle of the wheel colliders (as well as other thinigs)

buoyant crane
vagrant blade
#

Any comment following this that isn't that, is going to be another mute.

still ruin
#

could it be that it is modifying the spring value 2 scripts over? (using the harvesters script to reference the wheel colliders instead of modifying the wheel colliders directly from a wheel collider object inside of this script)

buoyant crane
still ruin
#

yeah, fd is a public float declared inside this script

buoyant crane
#

no i mean the fd in the image

still ruin
#

yeah, fd is local to this script

whole parrot
#

Thats it, thats literally what it is

#

Like I don't need to give people my code if you know what you're doing

vagrant blade
#

Well for starters, nobody would have guessed what errors your code clearly has, without you showing it.

whole parrot
vagrant blade
#

You're passing in a bool type, not your actual bool called name. These should be highlighted as errors in your IDE if you're using.

#

Don't be so insufferable. That means nothing without seeing the code, it's not that hard to understand.

#

Again, if you're going to continue being difficult in this discord, you will be removed. I won't say it again.

#

There's asbolutely not need to be argumentative. Show your code, get help. That simple, everyone does this without issue.

leaden solstice
#

What are you doing? bool is keyword not variable or value

whole parrot
leaden solstice
#

What is condition here, is that a random pseudo code?

whole parrot
cosmic rain
amber haven
#

Is there any way using a render texture, to render a cameras view from a separate scene?

vagrant blade
#

I mean, there's other issues too:

  1. You can't have two same named variables
  2. You have nothing called condition
  3. You have nothing called CubeMap to call apply on
vagrant blade
whole parrot
vagrant blade
#

Is this copy/pasted from your code, or are you summarizing? 🤔

cosmic rain
whole parrot
#

It should work considering it used to unless unity updated something in C# and now that doesn't work

leaden solstice
vagrant blade
#

@whole parrot Is this your code exactly as it's in your script , or did you summarize it with pseudocode?

cosmic rain
#

Aight... That pseudocode doesn't make any sense then.

vagrant blade
#

!mute 402958234371227648 1w Once again, you are refusing to share your actually code (for some reason). Nobody can help if they can't see your work, and you continue to waste people's time by dancing around that fact. As mentioned before, if you weren't going to share your actual code, you will be muted. This is your second and last one. I suggest when you return, you actually participate in receiving help the normal way, by showing your work and letting people assist you that way.

tawny elkBOT
#

dynoSuccess UnicornKitty#3889 was muted

cosmic rain
#

Share your actual code and a screenshot of the error, or no help for you.

vagrant blade
#

We'll try again in a week. Goodnight. wwi_wave_yellow

cosmic rain
#

Guess not then. 😄

amber haven
#

Is there any way using a render texture, to render a cameras view from a separate scene?

short ridge
#

👋 Hey, I keep getting this warning, I know why I keep getting it, and don't intend to fix it since it's basically irrelevant, But the warnings are clogging up my console, I know you can suppress it if you have the warning ID, but how do I get the ID?

cinder kindle
#
    private void HandleWalk()
    {
        if (!CanMove) return; // if you have walk disabled return
        if (characterController.isGrounded)
        {

            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical")); // Calculate the movement direction
            moveDirection *= WalkSpeed;

            if (Input.GetButton("Jump"))
            {
                if (!CanJump) return; // if you have jump disabled return
                moveDirection.y = JumpHeight; // Make the character jump
            }
        }


        moveDirection.y -= gravity * Time.deltaTime; // Apply gravity forces

        characterController.Move(moveDirection * Time.deltaTime); // Move the character controller
    }


Can someone help, does anyone know how to move the player move forwards in the direction of the camera? I've done this before but I forgot how and the scripts are on my broken hardrive.

cinder kindle
spark elk
#

I want to create a magnifying glass script that magnifies the canvas based game objects which are in screen space overlay I didn't found much references for this problem

prime sinew
# spark elk ```I want to create a magnifying glass script that magnifies the canvas based ga...

In this video I show you how to make a simple magnifying glass feature for your 2D game In Unity software.

TO BLAST! - My New Fun Relaxing Puzzle Game Available On Google Play Store
https://play.google.com/store/apps/details?id=com.ZoGames.ToBlast

Guess The Movie Is Available On Play Market For Free For Android devices
Here is the link
https:/...

▶ Play video
#

isn't this what you want?

cinder kindle
normal arch
#

does anyone know if there is anyway to add top down platforimg and jumping in a 2d game, like cross code or alundra, I've also herad that some old zelda games had thua feature as well, but I'm struggling to find tutorials that help with this, as all of them are using either gamemaker or godot, can anyone help me with this?

normal arch
#

you mean of the game

#

crosscode?

prime sinew
#

of what you mean by.. top down platforming and jumping

normal arch
#

ok I'll show you

#

it shows it in about 10 seconds

#

that's what im aiming for but with a manual jump button instead of automatic

prime sinew
#

logic is the same for any 2d movement. it's just the art that affects the perspective

#

try looking at any top down 2d movement tutorial

normal arch
#

ok

prime sinew
#

and if you're getting results for other engines, why not just add "unity" to your search

normal arch
#

i did but still there were no tutorials

prime sinew
#

pretty sure there are

#

where are you searching

normal arch
#

YouTube

prime sinew
#

Youtube is not a search engine

#

please Google

normal arch
#

on google there were no examples of code

prime sinew
#

and there wont be tutorials of EXACTLY what you want. that's game dev. you need to figure things out yourself sometimes

normal arch
#

it's just like psuedo code

#

that I can't really understand

prime sinew
#

if you're really new to coding and Unity, you should start with the basics

#

!learn
Unity Learn has some starting projects you can learn from

tawny elkBOT
#

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

prime sinew
#

as well as the beginner scripting course

normal arch
#

ill try and relook online to see if i can understand it better, because it's just a new concept to me

rancid kiln
#

yooo

#

need help'

#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    Rigidbody2D rb;
    public float speed = 6;
    public float rotSpeed = 0.2f;
    Vector2 mousePosition;

    public float dashTime;
    private float dashTimeCounter;

    public Slider dashBar;
    public float dashSpeed;
    public float dashFillSpeed = 0.5f;
    public bool dashfilled;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        dashBar.maxValue = dashTime;
    }

    private void Update()
    {
        mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        dashBar.value = dashTimeCounter;
        Dash();
        Move();
    }

    private void Move()
    {
        Vector2 dir = mousePosition - rb.position;
        float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
        rb.rotation = Mathf.LerpAngle(rb.rotation, angle, rotSpeed * Time.unscaledDeltaTime);
        rb.velocity = transform.up * speed * Time.unscaledDeltaTime;
    }

    void Dash()
    {
        if(dashTimeCounter >= dashTime)
        {
            dashfilled = true;
        }
        else if(dashTimeCounter <= 0)
        {
            dashfilled = false;
        }

        if (dashfilled == true)
        {
            dashTimeCounter -= dashSpeed * Time.unscaledDeltaTime;
            Time.timeScale = 0.2f;
        }
        else if (dashfilled == false)
        {
            dashTimeCounter += dashFillSpeed * Time.unscaledDeltaTime;
            Time.timeScale = 1;
        }
    }
}```
#

even tho im multiplying by time.unscaleddeltatime it still slows down the player

#

only the enemy should be shlowed

#

slowed*

#

help

hexed pecan
#

This looks wrong:

rb.velocity = transform.up * speed * Time.unscaledDeltaTime;```
You shouldn't multiply a velocity with a delta time value anyway. 
I suggest you try dividing it with ``Time.timeScale`` instead
rancid kiln
hexed pecan
#

I also suggest calling Move from FixedUpdate instead of Update, to avoid weirdness due to physics loop vs. rendering loop

#

And use rb.MoveRotation instead of rb.rotation if you want the rotation to look a bit smoother (you need to enable interpolation on the rigidbody)

rancid kiln
#
        float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
        rb.rotation = Mathf.LerpAngle(rb.rotation, angle, rotSpeed / Time.timeScale );
        rb.velocity = transform.up * speed / Time.timeScale;```
#

now it is jittery and not smooth

vestal geode
#

The jitters will likely disappear if you rework the physics methods into the physics update loop and remove the deltatime multiplications that conflict with it

hexed pecan
#

I can see in the inspector that the rb is still not interpolated

vestal geode
#

The engine doesn't calculate physics in the render loop, so you shouldn't be inserting 'time since last render frame' into any variables

rancid kiln
#

thanks you both

#

and i also had to interpolate just like @hexed pecan suggested

vestal geode
#

It will help you to read what the FixedUpdate is and how it should be used

rancid kiln
#

TYSM everyone

pale ore
#

how much more ressources does it need for unity to call a method from one script to another if this first script has a cached reference to the other one ? if this method is called in the update function is it really performance impacting?

lucid valley
hexed pecan
#

I think he means like calling a method from within the class vs. calling a method from another script?

#

Which should be negligible

lucid valley
#

sure probably is slower, but there's nothing you can really do about it

#

such a micro optimisation to worry about

hexed pecan
#

Yep

pale ore
simple egret
#

Almost exactly the same, and almost as performant

pale ore
#

okkk

#

thank you

simple egret
#

It just has to say "hey load where the other MonoBehaviour is in memory" for the second one, which is extremely negligible

lucid valley
#

the development gains from better organised code for such a negligible performance impact is always worth it

#

and you'll always find other places to refactor for better performance before thinking about moving methods around just for any slight increase

pale ore
#

this bulletSpawnTransform.position should give me its world position right ?

pale ore
#

so why when i shoot at two different positions i get this

#

this is the ingame transform of the bulletSpawn object

#

its debugging the local coordinates

#

not the world ones for some reason

lucid valley
#

is it a child?

pale ore
#

yes

simple egret
#

No it's logging the world position. What shows in the Inspector is the local pos

pale ore
#

yeah but the position its debugging is the rounded one of the local position

simple egret
#

Then the object has no parent

weary dawn
#

im getting the debug message "Look rotation viewing vector is zero". Should i be worried and how can i make sure it wont appear. Im following Codemonkeys 10 hour tutorial

pale ore
simple egret
#

Or the parent is at world origin

pale ore
#

it has a parent

#

not at world origin

simple egret
#

Sure you're looking at the right object? In the Hierarchy it's disabled, but the Inspector shows it enabled

pale ore
#

yeah the game was paused so i could capture it while active

simple egret
#

Try logging the localPosition then, because what you're logging is definitely the world position

#

It might be referring to a whole another object, log its name also

lucid valley
#

and if none of that seems to show why, then try looking at the positions of the parents and see if you are accidently moving them incorrectly

normal arch
# prime sinew as well as the beginner scripting course

i've made a script that i think will work the way i want it to, what do you think

public class HeightManager : MonoBehaviour
{
    public float playerHeight;
    public List<Collider2D> level0;
    public List<Collider2D> level1;
    public List<Collider2D> level2;
    public List<Collider2D> level3;
    public List<List<Collider2D>> levels;

    public void Start()
    {
        DisableAllLevels();
    }

    public void Update()
    {
        EnableCorrectLevel();
    }

    public void DisableLevel(List<Collider2D> level)
    {
        for (int i = 0; i < level.Count; i ++)
        {
            level[i].enabled = false;
        }
    }

    public void EnableLevel(List<Collider2D> level)
    {
        for (int i = 0; i < level.Count; i ++)
        {
            level[i].enabled = true;
        }
    }

    public void DisableAllLevels()
    {
        for(int i = 0; i < levels.Count; i ++)
        {
            for(int j = 0; j < levels[i].Count; j++)
            {
                levels[i][j].enabled = false;
            }
        }
    }

    public void EnableCorrectLevel()
    {
        if(playerHeight >= 0 && playerHeight < 1 )
        {
            DisableAllLevels();
            EnableLevel(level0);
        }
        else if(playerHeight >= 1 && playerHeight < 2 )
        {
            DisableAllLevels();
            EnableLevel(level1);
        }
        else if(playerHeight >= 2 && playerHeight < 3 )
        {
            DisableAllLevels();
            EnableLevel(level2);
        }
        else if(playerHeight >= 3 && playerHeight < 4 )
        {
            DisableAllLevels();
            EnableLevel(level3);
        }
    }
}

for people who haven't seen the previous messages, im trying to make a top down platformer

pale ore
#

this is the new output :

lucid valley
#

var parent = transform.parent;
while(parent != null)
{
    Debug.Log($"{parent.name} wp: {parent.position}, lp: {parent.localPosition}");
    parent = parent.parent;
}
pale ore
#

now its just debugging nothing ...

#

what the heck

#

its probably a event subscription error again that messes everything up

#

oh wait nvm

#

this is the output

#

weird, so the hierarchy doesnt detect parents

lucid valley
#

well that isnt parented then

pale ore
#

over the gun

#

but why is it parented in the hierarchy and not in the scripts

lucid valley
#

show the hierarchy fully open in playmode

pale ore
lucid valley
#

it doesnt have the (Clone)

#

so you must have two of them