#💻┃code-beginner

1 messages · Page 29 of 1

summer stump
#

This is not a code question, and please don't crosspost

hybrid mango
#

Hey guys, I have the following script! Basically it follows a tool that I use to delete objects in my building game. Inside the unity editor, it works flawlessly. The entire object lights up red to display that it is highlighted. However, when I build the project and try to play it, only the first material gains an emmision, not all of the materials in the object.
https://pastebin.com/Z6HknA6d

sour fulcrum
swift crag
#

Nah, that should be fine. The materials in the array are the exact same materials being used by the renderer

#

You only need to reassign the array if you assigned entirely new materials

buoyant knot
#

I make generic components (which might depend on other generic components). Then I might make a specific component (specific to the type of thing) that can GetComponent and use the generic components

#

Example:
Enemy has: SpawnedEntityHandler, EntityDataHolder, ObjCollision (depends on EntityDataHolder), GenericEnemyWalk (depends on ObjCollision)

#

Platform has: SpawnedEntityHandler, EntityDataHolder, ObjCollision (depends on EntityDataHolder), PlatformHandler (depends on ObjCollision)

#

Checkpoint has SpawnedEntityHandler, EntityDataHolder, CheckpointHandler (depends on SpawnedEntityHandler)

#

idk if this helps

slender path
eternal falconBOT
#
Posting code

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

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

slender path
sour fulcrum
#

How would I lerp a transforms rotation just based on a float?

Like if I want to make something turn to rotation.y 180

I quick google showed me Quaternion.Lerp and Slerp but the examples use a transform as a target rather than just a number

slender nymph
#

the examples use quaternions not transforms. those quaternions just happen to be the rotation of other transforms. you can create a quaternion from euler angles using Quaternion.Euler

amber spruce
#

so im making a player i used a asset for the model animations etc but for some reason only my camera moves on a differnt model the model also moved anyone know why this is happening

#

i would send my character controller but its to big

teal viper
#

It's not quite clear what you mean. Maybe upload a video demonstrating the issue.

slender nymph
#

also you can use a bin site to share large blocks of !code

eternal falconBOT
#
Posting code

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

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

amber spruce
#

so i figured it out lol i had 2 character controllers lol

#

mb

#

although i could use help with one thing when i look around my model doesnt turn with it the old one did

#

here is the controllerhttps://hastebin.com/share/bujofonona.csharp

slender path
slender nymph
#

get what info?

summer stump
slender path
#

it gives me the error

#

NullReferenceException: Object reference not set to an instance of an object

slender nymph
#

please provide the stack trace

#

you should already know how to find that from the link you were provided earlier

#

ah, i see. after going through your message history i can finally tell what your issue is. you are not assigning anything to your meshData variable anywhere so it is null

slender path
#

do you know how I would assign it

#

Also the stack traces are
TerrainGenerator.UpdateVisibleChunks () (at Assets/Scripts/Infinite Terrain/TerrainGenerator.cs:78)
TerrainGenerator.Start () (at Assets/Scripts/Infinite Terrain/TerrainGenerator.cs:43)

slender nymph
#

i mean, the stack trace is no longer necessary. but do you not know how to create an instance of a class and assign it to a variable?

slender path
#

MeshData meshData = GetComponent<MeshData>();

slender nymph
#

meshdata is not a component

slender path
#

i am finding that out

slender nymph
#

again, do you not know how to create an instance of an object?

slender path
#

i guess not

slender nymph
#

there are beginner c# courses pinned in this channel

#

you should start there if you don't know how to use the new operator

#

i'm also curious what data you think you are passing to that TerrainChunk constructor if you don't even have an instance of the MeshData

slender path
#

the verticies array

slender nymph
#

what data do you think is in that array?

broken anvil
#

anyway i can set the spawned bullet's transform positions and rotation to another object's transform value?

slender nymph
#

you can pass a position and rotation to the Instantiate method

slender path
#

Vector3 and Ids are in that array

slender nymph
broken anvil
#

like i need the spawned bullet to position itself on this transform

slender path
#

vertices [vertexIndex] = vertexPosition;

slender nymph
# broken anvil

also based on the fact that you are casting a double literal to a float instead of just writing a float literal, i recommend you go through some beginner c# courses. there are some great courses pinned in this channel

slender nymph
broken anvil
slender path
slender nymph
#

okay but if you aren't creating an instance of MeshData what data do you think is in the array you are trying to access?

#

hint: the array does not exist because you have not bothered to call the constructor for that object

slender path
#

what do you mean

slender nymph
#

meshData is null. you have not bothered to create an instance of it or even call that AddVertex method.

#

since you've not bothered creating the instance nor adding any vertices, what data do you think you are passing? the answer is obviously none.

slender path
slender nymph
#

now go look at your TerrainGenerator. where are you calling that method that creates the instance of the MeshData and assigning it to your meshData variable?

#

again, you are not

slender path
#

That is what i am here for

slender nymph
#

and that is what i've been trying to make you understand this whole time

#

but you clearly do not understand your own code otherwise you'd have realized you need to call that method and assign its return value to your meshData variable

#

so you probably need to go rewatch whatever tutorial you copied the code from and maybe try and understand what exactly it is doing and why

slender path
#

my only goal is to get the height of the mesh at a certain point and place a tree there

opal fossil
#

what version off c# and .net does unity 2023 use

slender nymph
opal fossil
#

thx

real dome
#

sorry if this is a novice question but is there any way for smooth rotational movement without using Quaternion.Slerp?

#

im trying to make a 2d submarine game and the submarine's direction always tries to face the cursor which is locked around the centre with a radius of 5f (kinda unimportant but dont worry)

slender nymph
#

since 2d would only rotate around the Z axis you just need to use Mathf.Lerp the one angle

#

or you can just use Quaternion.Slerp if you get a quaternion representing the desired rotation. which is also fairly trivial

real dome
#

i think ill try Mathf.Lerp because when i tried using Quaternion.Slerp i got my desired effect but

#

its kinda hard to explain

slender nymph
#

i'd bet the issue lies with how you get the desired rotation

real dome
#

hold on ill just send a video

#

im getting the desired rotation through the tracking of a transform object

slender nymph
#

i'd rather see your code

real dome
#

you see how it sorta like flips once it passes the middle threshold

#

as for the code here it is:

slender nymph
#

!code

eternal falconBOT
#
Posting code

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

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

real dome
#

whoops

slender nymph
#
Quaternion rot = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direct), rotSpeed * Time.deltaTime);
rot.y = 0;
rot.x = 0;

yeah that's not right

real dome
real dome
#

kinda lazy but it worked until well

real dome
slender nymph
#

well for one Quaternion.LookRotation creates a quaternion that represents the Z axis pointing in the direction you provide. also quaternions are not euler angles and you should not be modifying them manually like that if you do not understand how they work. their axes are not in degrees

#

if you just want the desired Z rotation angle you can use Mathf.Atan2 to get the angle from the direction. then you can create a quaternion using Quaternion.Euler for the target rotation. or if you are using a rigidbody you could instead use its MoveRotation method

frail adder
#

Hi, my code for jumping using rb is being really weird as every single time the character jumps, the height of the jump is either high or really low. Why is this happening?

frozen mantle
#

hey all, i want to have a aggro system where the enemy will stay aggroed on the player for 5 seconds after the player has left it's range. in order to keep track of these 5 seconds, is it faster/more optimized to user a time variable, or to use coroutines?

slender nymph
slender nymph
#

any actual performance differences will be entirely based on implementation though

real dome
#

if you just want the desired Z rotation

frail adder
frozen mantle
slender nymph
#

right which is why i said that potentially starting a bunch of coroutines quickly will be less performant than just using a timer in update since you can just reset a float for that

frozen mantle
#

i think with that i would only ever have one coroutine going at a time? tho, that;'s one coroutine per enemy... tho, i don't plan to swarm the player with more than like, 3 enemies at once

slender nymph
frozen mantle
#

You think im overthinking my code by using coroutines?

#

im just trying to get into the habit of writing optimized code

unique violet
#

How can I keep my self organized instead of having right now 50 scripts. My big thing is having data scripts on parents that have variables for there child’s.

static cedar
#

Tbh, i'm preferring async over coroutines. UnityChanThink

slender nymph
# frozen mantle You think im overthinking my code by using coroutines?

it depends entirely on how you decide you want to handle it. like i said starting a bunch of coroutines quickly is less performant than just using a timer in update. but compare to a timer in update, a timer in a single coroutine instance has nearly no performance difference. the only difference is the initial start for the coroutine (i have a benchmark that shows this somewhere, i'll try and find it real quick)

frail adder
#

this is how i move the player, would this conflict with it?

frozen mantle
slender nymph
slender nymph
frozen mantle
#

im just trying to understand is all

#

im sorry

#

please have patience

#

i just, i feel like my code it really sloppy in all honesty and i wanna start making good code

slender nymph
# frozen mantle please have patience

as i have already told you, any performance difference will entirely depend on the actual implementation. you can discuss theory all you want, but that doesn't mean shit if you end up writing it poorly anyway

frozen mantle
#

so what am i to do? just implement both methods and check the profiler?

#

sorry i don't mean to upset you

#

im just a tad lost

slender nymph
#

you should focus on just implementing it in whatever way makes the most sense to you. then if you happen to have performance issues, you can refactor if necessary

#

just work on it, don't worry so much about squeezing every single drop of performance out of the code otherwise you'll never get anywhere

frozen mantle
#

im trying to avoid refactoring but i guess that's just the life of a game dev

#

okay, thank you

#

i know you get bombarded with dumb questions and tend to lose patience quick

#

i apologize for contributing to that

charred spoke
frozen mantle
charred spoke
#

Why?

frozen mantle
#

it's supposed to be a "test" project, even tho i've been working on it for a year

#

idk i just want to

charred spoke
#

The moment you write code yourself

#

Its no longer a built in solution

#

🤣

frozen mantle
#

i don't wanna use outside libraries

charred spoke
#

Why?

frozen mantle
#

sorry im just

#

kinda frustrated

slender nymph
#

don't reinvent the wheel if you don't have to.

frozen mantle
#

gimme a quick second to gather myself

charred spoke
#

Im genuinely curious about it. Ive seen many new folks refuse to use ready made and tested libraries, while most senior dev would like nothing more than that. I hate writing code someone else has already written.

static cedar
frozen mantle
#

okay

static cedar
#

That's just me ig.

frozen mantle
#

sorry im back i just felt bad because i don't mean to waste any of y'alls time

#

im just trying to make good habits is all

#

and i guess the imposter syndrome is deciding to hit me a bit, but i'll get it over soon

charred spoke
frozen mantle
#

i guess the reason i don't wanna use libraries is i feel it complicates things?

#

and also makes it hard to ask for help if i use outside libraries in case my code explodes

slender nymph
#

typically they simplify things, though it can feel complicated while you learn how to use it. but it's not really any harder than learning how to implement it yourself

frozen mantle
#

true

#

also, with this specific library

#

i don't feel like going back through my code to implement it, i could just say screw it and just go ahead and only use it from this point on

#

but then my code is gonna look all sloppy

frozen mantle
#

in this Dev's opinion, it "hides away game logic"... whatever that means

#

but i guess it's a worry to someone

static cedar
frozen mantle
#

Yeah kinda sorta same

static cedar
#

I feel like spouting random crap at times. UnityChanThink

frozen mantle
#

i mean it's very handy and i appreciate it!

#

just think it's a tad overkill, so to say

#

imma just keep it stupid simple and use a timer

#

thanks all!

#

@slender nymph @charred spoke i appreciate you two's help, again sorry if i was being stubborn or annoying i just wanted to be sure i understood fully what was going on

#

brain is dumb sometimes

charred spoke
#

It’s okey. I suppose I was the same when I started. You will grow and learn

frozen mantle
#

libraries are gooood

#

so you're advice is not falling on deaf ears

slender nymph
#

you could always learn to implement it yourself in a way that can be reused like that package that uri linked then you'll have your own version of it to pull into your projects that will suit your needs exactly

static cedar
#

The only library i used quite a bit is Unitask. UnityChanThink

#

Pretty much a library to make async work pretty well since i'm not using coroutines.

static cedar
#

Though, ams currently, not working on my game, just a discord bot that scrapes my school web.

final trellis
#

making an audio player with "+ and - 5 second" buttons, getting this error despite clamping, anybody know a fix?

broken anvil
#

heya how do you make it so instantiated objects have suffixes like (1), (2), and so on

#

if multiples are spawned on every trigger

slender nymph
#

you can modify a gameobject's name property. but that would also require you to keep track of how many have been spawned. but honestly, what is the point in doing this?

static cedar
#

It looks nice.

#

I don't want to see unnamed stuff in the heirarchy. UnityChanThink

slender nymph
#

i mean, it wouldn't be unnamed. it would have the prefab's name with (Clone) appended to it. it just wouldn't have the numbers at the end that they seem to want 🤷‍♂️

broken anvil
rich adder
#

why use names instead of an array or something?

slender nymph
final trellis
slender nymph
#

a Queue would probably be even better

frozen mantle
#

oh, data structures

#

this is something im good at

#

i went to college

#

🤓

broken anvil
slender nymph
#

you shouldn't be relying on gameobject names for your logic. that will make it incredibly brittle

final trellis
ashen ferry
#

keep seeing this thing to not use names for anything

#

why is it brittle its as brittle as any string comparison noones gonna change gameobject name but you no?

slender nymph
#

there's nothing preventing a gameobject's name from being changed by other objects. it also relies on making sure your spelling is exactly correct with no compile time checking for that so if you spelled something wrong, you won't find out until you run it and hopefully notice that the code isn't doing what it should

#

also if you are searching for gameobjects by name using something like GameObject.Find then you are searching the entire hierarchy which can be incredibly slow in larger scenes with more objects

#

plus, the behavior they want to achieve can be done using a collection and just storing the objects when they are spawned in the correct order (such as with a Queue or Stack, or even just appending them to a List) instead of relying on any string comparisons at all

charred spoke
ashen ferry
#

no but like I used gameobject name for my object pooling and it was 100% percent fine u set animator params with string names or shader property with string as well theres some stuff where u "blindly shoot" into it but as long as it doesnt change randomly how is it bad

charred spoke
#

Well its slower

ashen ferry
#

tho what did u mean with there's nothing preventing a gameobject's name from being changed by other objects. part

#

god damn forgor how to quote kekW

charred spoke
#

Shader properties can be converted to ints statically

#

So can animator params for that matter

ashen ferry
#

huh so im just retarted then

charred spoke
#

Mno you just never hit a scale where that matters

ashen ferry
#

what scale we talking about

slender nymph
charred spoke
#

Performance or team wise

ashen ferry
#

yea fair point ig cant argue

ashen ferry
charred spoke
#

I dont have exact numbers

#

Like 5 team members and 20-30 animators running at once

ashen ferry
#

how is this thing called to change shader properties with ints

#

cant open ide rn and neither do I find anything

#

u still got a string in here

charred spoke
#

Yes but you call this once and store the result in a static or const variable and use that

#

That way there is no calculation and no garbage when calling for example animator.GetBool or what ever

ashen ferry
#

this just as its states for performance u can store static string as well

#

still blindly hope u typed it in correct

charred spoke
#

Sure but unity does the hashing anyways

charred spoke
pearl grotto
#

I am absolutely terrible with quaternions, I've been spawning soemthing using a vector3 + transform.forward, and i think it would work much better if i could just take the x z rotation of the player and not the y

#

looking up and down causes some weird collisions with my player and bounces them around lol

charred spoke
ashen ferry
#

damn this would be nice to have if my animators wouldnt be with like 2 animations at most kekW

frozen mantle
#

nah im joking

#

this looks handy too

charred spoke
#

It is an old library I might fork it and give it an update

ashen ferry
#

over engineered as fuck it must get pretty bad when u got a lot of animations for this to exist

charred spoke
#

I bet it will still work on modern unity, the animation api has not changed at all

frozen mantle
#

maybe you can clean it up, Uri

#

and make it not over engineered as Blin thinks it is

charred spoke
#

I wouldn’t call it over engineered. It seems to handle every case I can think of

frozen mantle
#

ye

charred spoke
ashen ferry
#

What yall cooking gta 7? kekW

real dome
#

sorry for interrupting guys but im back to my old problem where ive been trying to ease in and out of rotational movement but its just giving me immediate rotation, the "angle" float is my desired rotational value of rb
https://paste.ofcode.org/tTfSvt4CbwZ8fFt5fLr9BC

hybrid karma
#

ive been using doubles for my money in my game but im finding issues with imprecision, can i just swap a double with a big int and everything be fine?

charred spoke
hybrid karma
#

at early stages kinda? but at later stages the numbers are so high it wont matter

charred spoke
#

Can your money go negative?

hybrid karma
#

no

charred spoke
#

Wel ulong is your best bet then

frozen mantle
#

okay i think the time implementation is fine, works smoothly and is readable in code

#

tho, my boolean statements got a bit longer, but so is the pitfalls of AI

hybrid karma
#

ulong is hundreds of magnitudes less than i need

charred spoke
#

Ah this is a cookie clicker type of game. i suppose BigInteger then yes

magic hawk
#

Hey i was just wondering if anyone could help me learn how to make an action counter that increments every time a UI button is clicked?

summer stump
magic hawk
#

Alright i have that, I was also wondering how to apply that to on screen text because it only shows it increment in the Inspector. For example i have text that says "Actions" and I would like it to go up by 1 every time a UI button in clicked. Sorry if this is a lot i just suck with UI lol

summer stump
#

Keep in mind the type of the variable needs to be right. You should be using Text Mesh Pro, so the Type should be TMP_Text, and you'll need using TMPro at the top.

On my phone, so can't remember the capitalization, but I think that's it

If you try to put a TMPro text into a Text type field, it won't work

magic hawk
#

dont worry i have TMPro on lol

#

ALRIGHT I GOT IT WORKING

#

thank you very much you are a massive help

queen adder
#

guys, how can i make a script where if that gameobject is touched the players gravity gets switched

slender nymph
#

well first, don't crosspost

queen adder
#

i accidentally posted it there and i realised there is a code-beginner channel

slender nymph
#

but you need to break it down into smaller steps that are more easily solved. what part about that specifically are you not sure how to accomplish?

queen adder
#

well

slender nymph
queen adder
#

so when the object which the script is attached to is touched

#

the players gravity goes from lets say 2 to -2 and also it rotates the players Z axis by -180

#

most tutorials i found are on when u press a key gravity changes but i dont want that

slender nymph
#

okay so then there are three steps you need to figure out how to accomplish:

  1. how to detect collisions
  2. how to change how gravity affects the player
  3. how to rotate the player
queen adder
#

well this is what ive done so far

slender nymph
queen adder
#

oops

#

accidentally put wrong comment

slender nymph
queen adder
#

ok

slender nymph
#

but here you would just get the player's rigidbody2d and change its gravity scale as well as rotate it

queen adder
#

so i'd need to do something like GetComponent(Rigidbody2D)

slender nymph
#

yeah, but that's not quite how you use GetComponent

#

you also need to make sure you call GetComponent on the player object not the object that this script is attached to

queen adder
#

oh

#

hmm

#

i dont get it

fiery sedge
#

Hi! I want to create a timer. I've tried it in Update and it works perfectly.

private float _time;
private void Update()
{
    if (_time < seconds)
    {
        _time += Time.deltaTime;
    }
}

But if I try it in another method it works very quickly.

private void WaitForSeconds(int seconds)
{
    float time = 0;
    while (time < seconds)
    {
        time += Time.deltaTime;
    }
}

Maybe because Update is called every frame and while doesn't. Help me, please, with it! Thanks.🥰

slender nymph
slender nymph
#

this is a code channel

queen adder
#

then wait

slender nymph
#

that doesn't mean you should post in an unrelated channel

slender nymph
slender nymph
#

so call GetComponent on the incoming collider if it has the Player tag

queen adder
#

thanks

low perch
#

how do I avoid an error if hit is null or something else

if (hit.collider.gameObject.GetComponent<click_point>() != null)
    {
        hit.collider.gameObject.GetComponent<click_point>().transport();
    }
slender nymph
#

start by checking that hit.collider is not null

static cedar
#

Did you check if hit.collider is null.

#

Ok wa.

obsidian jewel
#

i have 2 monster make by spine animation 2d. I need combine some part of them to new monster. the problem is it too different from 2 part animation and bone so i cant just swith their skin.

ruby python
#

Hi all, I'm kinda losing the will to live over here at the moment, so I really hope that someone can help figure out what I'm doing wrong..........

I've followed this video to make a simple script to open and close a door, but I just cannot get it to work at all.

https://youtu.be/7t218LaeiiI?si=8ztRcEgCOOT0htky&t=277

((Code to follow......))

In under 5 minutes we write code for opening and shutting a door without the use of animations!

Link to Project: https://github.com/dustinmorman/OpenDoorTutorial

Link to download the door asset: https://drive.google.com/file/d/1QPmQF3thm-hIMugoZxGr72vAjdgz551x/view?usp=sharing

Link to my Upcoming Game - Survive the Uprising: https://store.ste...

▶ Play video
#

https://pastebin.com/sdUCd5g7

My closeAngle is 40 and my openAngle is -15

When I open the door, it seems to work but when it gets close to reaching its target, it 'flips out' and snaps to trying to be at 90 degrees, and the closing just doesn't work at all (I'm guessing because of the flipping out). At the moment I'm just using the inspector to flip the bool on and off.

keen dew
#

You can't take the angles from the object's current localEulerAngles. You'll have to use a separate variable.

#
private Vector3 currentRot;

private void Start()
{
    currentRot = new Vector3(closeAngle, 0, 0);
    rearDoor.transform.localEulerAngles = currentRot;
}

void Update()
{
    if (isOpening)
    {
        if (currentRot.x > openAngle)
        {
            currentRot = Vector3.Lerp(currentRot, new Vector3(openAngle, currentRot.y, currentRot.z), doorSpeed * Time.deltaTime);
        }
        else if (currentRot.x < closeAngle)
        {
            currentRot = Vector3.Lerp(currentRot, new Vector3(closeAngle, currentRot.y, currentRot.z), doorSpeed * Time.deltaTime);
        }

        rearDoor.transform.localEulerAngles = currentRot;
    }
}
#

Terrible tutorial btw

ruby python
#

Aaah okay, weird how it worked in the vid. lol. And I know there are better ways, just seemed like the quickest, and I reeeeeally don't want to use the Animator. lol. Thank you though, very much appreciate it.

keen dew
#

It can work by accident for some values but Euler angles are not unique so they're not reliable for this kind of thing

ruby python
#

Okay, gotcha.

#

That works great, thank you. 🙂 Now just need to figure out why the thing won't close after it's open. lol.

loud dragon
keen dew
#

The object doesn't have a text component so CounterText is null

loud dragon
#

done but still same

unique hull
#

What line is the null reference on?

keen dew
#

done what?

loud dragon
#

i think 37

#

i made countertext public and add text component on inspector

keen dew
#

Did you remove the line from Start that re-assigns it?

unique hull
#

Yeah the start function tries to grab a text from the current gameobject. If that is null , then the text becomes null.

loud dragon
#

yes

keen dew
#

Show what you have now

loud dragon
#

now its not showing error

#

but

#

my targets are not spwaning

unique hull
#

Have you assigned a bullet prefab?

#

What line is it breaking on?

#

Does it break on the "if" line or on the "Instantiate" line ?

amber spruce
#

anyone know why my model doesnt turn with the camera the old model with the same scripts did i changed the model and now it doesnt here is the player controller https://hastebin.com/share/bujofonona.csharp

loud dragon
#

https://hastebin.com/share/ukececizoq.csharp
https://hastebin.com/share/orepeyanix.csharp
In these above it is entering targetspawner function but not in the condition also in bullet_destroy the ount is decreasing but it is not getting updated in counter

lean basin
#

Hello, since unity button doesn't have hover, and select event. I intend to make my own. I can use ISelectHandler to create Selected event, I can use IPointerEnterHandler to create hovered event. But how do I be able to navigate between my buttons using keyboard leke the built in button does?

gray pilot
#

If there is more than one bullet_destroy script, they would each have their own separate counter variables

#

You also only reference one bullet_destroy script in your counter class, which one?

topaz mortar
#

I have Item, which is a MonoBehaviour
If I do Item newItem = newItemObject.AddComponent<Item>();
How would I set the fields of my newItem?
Is there a constructor or something?

tacit estuary
#

You should make it a prefab instead of a game object in the scene. If the original bullet is destroyed, it can no longer make copies of the original

polar acorn
topaz mortar
#

so there's no default constructor?

#

idealy I would add parameters to the AddCompentent<Item>(...)

tacit estuary
#
void SomeInitializer(int a, bool b)
{
    // treat this as a constructor
}

// How you would use it
Item newItem = newItemObject.AddComponent<Item>();
newItem.SomeInitializer(99, true);```
tacit estuary
polar acorn
lilac hemlock
#

Can someone help me please? I am building a grid based placement system. I want to calculate size of an object in cells and then mark it. However, I can't make the script to calculate size of an object is cells correctly. Also, if half cell is taken, i want it to count as one.

https://gdl.space/ejoqijosan.cs

topaz mortar
#

public void Create(ItemSO newItemSO)
{
    Debug.Log(newItemSO.ItemSprite.GetType());
    _image.sprite = newItemSO.ItemSprite; // This is line 25
}
dry tendon
#

Is there any way to detect sunset in real life and make something happen in the game?

rich adder
#

anything is possible

dry tendon
topaz mortar
#

I know what a NullReferenceException is, but I can't figure out what I didn't set

#

I literally debug the thing I'm setting right above and it's a sprite

rich adder
#

screenshot entire debug window not cutoff

topaz mortar
#

that's everything

#

maybe I need to instantiate the gameobject my item script is on?

rich adder
#

its not

topaz mortar
rich adder
#

ok and which object is this script on

#

screenshot

north kiln
#

It's also possible that you call the function twice and either newItemSO or ItemSprite is null the second time it's called

topaz mortar
#
Item newItem = newItemObject.AddComponent<Item>();
newItem.Create(monster.ItemDrop);```
north kiln
#

Well, _image or newItemSO can be null

rich adder
#

tryina see if _image wasnt set

deep folio
#

can somebody tell what is wrong

#

xpSlider.Value = PlayerXp;
xpSlider.maxValue = PlayerNeededXp;

north kiln
# deep folio

Your !ide should autocomplete so you don't make basic capitalisation issues

eternal falconBOT
#
💡 IDE Configuration

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

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

VS Code*
JetBrains Rider
Other/None

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

north kiln
#

Also errors should be underlined in red

topaz mortar
#

_image is a private field of the class

rich adder
#

no bro, the inspector

north kiln
#

The instance of the component in the inspector

topaz mortar
#

it's not created because of this error

rich adder
#

wut

rich adder
north kiln
#

The component with the Create function.

queen adder
#

What's a good game to start off with I don't know any coding

topaz mortar
north kiln
rich adder
#

pong / angry bird

#

yea flappy good too

queen adder
#

Ok

north kiln
topaz mortar
#

no it's not on a gameobject, I'm making a new gameobject with that script on it

#
Item newItem = newItemObject.AddComponent<Item>();
newItem.Create(monster.ItemDrop);```
north kiln
#

Then how is _image ever set

#

it is null.

#

Preferably spawn a prefab that has it already set up

topaz mortar
#

I think I can't work with prefabs since all items will have unique stats

#

that are generated when the item is created

north kiln
#

You can set the values on the instance just fine

rich adder
#

[SerializeField] isn't needed unless you did need the private field to show inside the inspector and want to assign it there

topaz mortar
#

everythign works just fine if I comment that one line

#

I don't understand why you're asking me if _image is set when that is the field I'm trying to set?

north kiln
#

you're not trying to set it, you're trying to use a field on it

#

_image.sprite = newItemSO.ItemSprite;
This is what you're trying to do:
null.sprite = newItemSO.ItemSprite;

topaz mortar
#

oh

#

hmm

#

wait what?

#

it's a field in my class? how can it be null?

#

I define it at the top of my class?

rich adder
#

defining != assigning

#

You declared it, thats good. But if you don't assign it, then it doesn't know where to point at..

swift crag
#

I would call it a declaration

#
public Foo myFoo;
#

This declares that your class contains a field called myFoo. The accessibility of that field is public. The field's type is Foo.

#

By itself, this does not do anything to construct a Foo or to find a Foo that already exists.

#

It simply declares that your class can store a Foo.

topaz mortar
#

and what I'm trying to do is myFoo = "sprite";
and I know the "sprite" is not null?

#

since I debugged it

swift crag
#

That would be fine.

#

But that is not what you are doing.

#

You are attempting to assign to the sprite property of an Image.

rich adder
swift crag
#

You must have an Image to be able to assign something to its sprite field

rich adder
#

its the component of the image

topaz mortar
#

so my gameobject doesn't have an image component?

rich adder
#

its like saying "Come Do this work in my Kitchen at My House"
but you dont give someone the address to your house

swift crag
#
public Image image;

public void GiveImage(Image theImage) {
  image = theImage;
}

public void GiveSprite(Sprite theSprite) {
  image.sprite = theSprite;
}
#

These are two very distinct situations.

north kiln
topaz mortar
#

I do not understand anything you're saying 😦

swift crag
# topaz mortar so my gameobject doesn't have an image component?

You could have an Image component somewhere else in the scene. You could have an object named "Image" with an Image component on it. You could have an Image component on the same game object.

None of these would result in your image field containing a reference.

topaz mortar
#

well I understand, but it doesn't make any sense to me*

rich adder
#

You need to simply tell where your image component is through assignment =

#

the computer doesn't know

swift crag
#

C# will not just randomly guess what you wanted to do.

#

you MUST do something to assign a reference to that image field.

#

The script must know which Image it's working with. It would be nonsense if it just...found some random Image somewhere.

north kiln
#

image is null, it was never set, you are trying to access a field (sprite) on it.
It was never set, an image doesn't exist there, you cannot set a sprite on something that does not exist

swift crag
#

When the code runs, that image field will not be null: it will hold a reference to the Image you picked.

rich adder
#

they already have an Setup -like method they pass SO, all they need to do is pass the Image component as well

topaz mortar
#

ah okaj I think I got it

rich adder
#

newItem.Create(monster.ItemDrop);

north kiln
#

Or just use a prefab and instance that instead of wholly creating it from scratch

swift crag
topaz mortar
#

at least it's working now, not sure if it's doing what I want though lol

swift crag
#

Every item instance in your game will need an image

rich adder
#

I'm guessing this some type of Image component in the scene already

north kiln
#

Who knows lol

topaz mortar
#

nah I just forgot to add the image component lol

#

didn't realize

#

and didn't understand what you were trying to explain

#
Image newImage = newItemObject.AddComponent<Image>();
Item newItem = newItemObject.AddComponent<Item>();
//Instantiate(newItemObject, newImage);
newItem.Create(monster.ItemDrop, newImage);```
#

but I will try to make it in a prefab instead

rich adder
#

yes do that lol

dry tendon
#

Heey, is there any way to detect sunset in real life and make something happen in the game?

swift crag
#

first thing that comes to mind: find a web service that can tell you when sunset is at a given location

rich adder
#

^

swift crag
#

The math probably isn't that hard, but there's just enough complexity with stuff like leap years, daylight savings time, leap seconds...

ripe shard
#

All the date intricacies are solved by the DateTime class

swift crag
#

looks a little frightening

wise fractal
#

yo can someone help with code here

rich adder
#

you mean chat GPT give you shitty code? shocker lol

wise fractal
#

so you guys can't help?

lean basin
#

Excuse me, when a gameObject is put inside canvas, it will have RectTransform component. But why can't I call this component? I have a reference of a component, how do I get the RectTransform from that?
I can't do this: someComponentsObject.gameObject.rectTransform

rich adder
wise fractal
#

ok bro so basically what I'm trying to do is basically a flag buidling

north kiln
ashen ferry
#

never knew u can cast transform into rect one they are a bit different wtf kekW

rich adder
#

its handy af

swift crag
#

RectTransform derives Transform.

#

It is a more specific kind of Transform.

ashen ferry
#

aaaa

swift crag
#

Every GameObject must have a Transform. Any type compatible with Transform will work.

ashen ferry
#

alright then will use that next time instead of GetComponent lmfao

wise fractal
#

which is basically like there is button which consist of Build, Lock, and Remove the thing is Im struggling with the removing part, where im trying to replace the cursor to be a UI within the game (replace cursor with UI), so when click "remove" a circle would appear and that game Object would be gone, and once clicked again the UI circle would be gone, leaving a normal cursor.

#

heres the code

swift crag
#

You can also use GetComponent<Transform>(), incidentally

#

nothing special about RectTransform there

#

Transform is a kind of Component.

wise fractal
#

let me upload as file

#

1000 word exceed

rich adder
#

!code

eternal falconBOT
#
Posting code

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

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

swift crag
#

share your code correctly.

wise fractal
#

ok bro

lean basin
#

ah very well. Thank you.

one more follow up question. Can I do this in one line?

RectTransform rectTransform = (RectTransform)buttons[id].transform;
targetYPosition = rectTransform.anchoredPosition.y +yOffset;

this is what I tried:

targetYPosition = (RectTransform)(buttons[id].transform).anchoredPosition.y;

but.. it doesn't work.

swift crag
#

Wrong order.

#

You are casting after trying to get anchoredPosition.y out of the Transform

#
((RectTransform) buttons[id].transform).anchoredPosition.y;
(buttons[id].transform as RectTransform).anchoredPosition.y;
#

Both of these would work.

north kiln
#

Don't do as

lean basin
#

oh I put the brackets wrong. thank you again

swift crag
#

The . operator has extremely high precedence. It goes before everything else.

swift crag
#

i guess you'll get null instead of an exception

north kiln
#

It is slower, and you'd just trade out a cast exception for a null reference

#

which would be confusing the issue

rich adder
amber spruce
#

how do i get a public static variable to show up in the inspecter

rich adder
#

you dont

#

static doesnt belong to an instance

wise fractal
#

so basically instead of the cursor being a UI like requested in the script, the cursors just disappear as well as adding random flags in random cords which was weird

rich adder
wise fractal
#

I don’t t know if it’s about that or the UI

#

I already added it separately in inspector for UI

#

If can not it’s fine bro I need to go to sleep anyway

rich adder
#

come back to it with a fresh mind and start debugging your positions etc

wise fractal
#

👍 thanks again bro

buoyant knot
#

i had more ideas about reference framing, if someone will listen

#

Recap; dynamic rigidbody on moving kinematic RB platform, and need dynamic RB to move in the reference frame of the platform, with no friction and avoiding setting transform

#

New idea; Platforms get surface effectors, set to their current speed based on their transform shift. Would this work?

#

oof, platformeffector2D and surfaceeffector2D conflict with each other

topaz mortar
#

Does this work if Inventory is a script reference on a Gameobject that is referenced on the character gameobject? 😛
newItemObject.transform.SetParent(character.Inventory.transform);

#

I guess it does 🙂

uncut dune
#

does OnDestroy() run after the object dies

#

I want to spawn something from enemies that deals damage when it collides with them but I can spawn it before they get destroyed or it will just apply to the dying enemy

#

will OnDestroy() fix my issue?

buoyant knot
rich adder
uncut dune
#

I want when an enemy dies to spawn something that deals damage to enemies and gets destroyed when they collide

#

if I instantiate before it dies

#

on top of the enemy

#

it just gets destroyed

uncut dune
rich adder
#

just dont make it child of enemy

buoyant knot
#

I have a component called SpawnedEntityHandler that goes onto anything that can die/despawn. All my scripts (instead of calling destroy), call OnEntityDeath / OnEntityDespawn in the spawnedEntityHandler

#

this system is immensely useful

rich adder
#

when do you call Destroy() ? just call Instatiate there

uncut dune
buoyant knot
#

this way spawned entity handler can handle what happens when you have a request for an entity to die

uncut dune
uncut dune
#

not sure why

rich adder
#

Nah I said call it when you call Destroy()

#

this is something else

uncut dune
#

this is what happens when I do that

rich adder
uncut dune
buoyant knot
#

my SpawnedEntityHandler also has an event Action onEntityDeath, which is invoked when an entity dies. So other entities/scripts can listen to the common request that an entity is about to die

uncut dune
uncut dune
#

sounds like a good practice

uncut dune
#

thats how it is supposed to work

rich adder
#

clearly

#

so how do expect to spawn it on something if it instantly destroys it

uncut dune
#

you clearly are not following, I just wanted to spawn something AFTER the enemy got destroyed

rich adder
#

I get it..

uncut dune
#

so?

#

whats wrong with it

topaz mortar
uncut dune
#

also I got it working now, @buoyant knot thank you so much

buoyant knot
#

so if a fireball hits a goomba, EntityLogic calls spawnedEntityHandler.EntityDied().
Then other things listening (like let's say a hat that the goomba has on its head or something), that can listen to OnEntityDeath. So when SpawnedEntityHandler calls OnEntityDeath?.Invoke(), now the hat knows that the goomba it's tied to is dead

subtle hedge
#
Vector3 pointDirection = drivePoints[pointIndex].position - transform.position;
transform.rotation = Quaternion.LookRotation(pointDirection, Vector3.up);
```how can i make it smooth, beacose it's snapping instanlty
rich adder
#

RotateTowards

dry tendon
rich adder
#

ubication permissions?

dry tendon
#

and how could i take latitude and longitude

dry tendon
dry tendon
#

oh, thanks

rich adder
#

so you want to code or add to this toolkit ? not sure what you're asking

#

Do you have a decent amount of experience with coding Unity Editor scripts?

short hazel
queen adder
#

I wasn't discussing that

short hazel
#

Decompiling or modding altogether

gray arrow
#

Hey guys, really new unity developer here, i am trying to do a very simple first 2d game - a top down shooter - which has the very classic line of sight effect using a mesh. i am trying to make it so that certain objects that are outside of the field of view are not visible. there was one tutorial online that I was able to follow to an extent, however the URP upgrade has made most of it useless to me. Instead of using the URP i have decided to do some angle calculations to determine if the object is within the fov of the player - however I have spent hours trying to get the right formula and put it correctly into code. Here is where I'm at rn:

float dx = transform.position.x - player.transform.position.x;
float dy = transform.position.y - player.transform.position.y;
float angle = Mathf.Atan2(dy, dx) * Mathf.Rad2Deg;
float playerRotation = player.transform.rotation.z * 180;
float DisFromNormalLine = angle - playerRotation;

//for debugging i print some variables to the console:
print(DisFromNormalLine + " " + playerRotation + " " + angle);

which gives me this effect, which gets less accurate the further away from (0, 0) you get (the capsule on the right is the "test object" running the script above):

timber tide
#

If you want to delve into URP render objects you can mask layers with stencils

gray arrow
#

yeah i tried that, thats why the entire screen is slightly greyscaled, but I couldnt get it to work so i resorted to maths.

timber tide
#

Ah, yeah I can see some difficulty preventing the light going through the wall

#

Actually, the mesh idea and adding depth such that you have a cone would probably work

gray arrow
#

what do you mean?

timber tide
#

Basically what you're doing, but you'd obtain less popout effect

gray arrow
#

i still don't understand sorry

timber tide
#

Is your problem just that you're trying to spawn enemies that are touched by your light source?

#

or rather, make them render onto your screen

gray arrow
#

im trying to make them visible if they are in the line of sight yes

#

not spawning anything new

timber tide
#

Ah, ok yeah. So technically if you got the mask working, if you do want to try out the URP render objects you can pretty much layer your enemies and your mask so they would be exposed when they collide through stencils. This would also eliminate the popin effect you got going which makes it more natural

loud dragon
#

i am atking reference from one script to another but whne value is getting updated it is not showing on the other script
Help

gray arrow
#

but i did try, like i said earlier the greyscale is a big mask

timber tide
#

They are part of the URP render asset now instead of just individual components

#

very similar to built-in

gray arrow
#

i have all the layers set up but idk how they work

#

thats the real issue

timber tide
# gray arrow

Something I've got to play around with since I've not touched them for a while, but seeing what you got I'm pretty sure you can make it work.

tender stag
#

so i have different like item types, and i need to be able to do something along the lines of if(item.maxDurability > 0) ```cs
using UnityEngine;

public class WeaponItem : Item
{
[Header("Durability")]
public AudioClip breaking;
public float durability = 0;
public float maxDurability = 0;

[Header("Statistics")]
public float damage = 0;
public float speed = 0;

[Header("Ammo")]
public int ammo = 0;
public int maxAmmo = 0;

[Header("Recoil")]
public Vector2 recoil;

}```

using UnityEngine;

public class ConsumableItem : Item
{
    [Header("Statistics")]
    public float health = 0;
    public float hunger = 0;
    public float thirst = 0;
    public float stamina = 0;
}```
#

all types of items inherit from Item

#

how do i go around this?

#

because i only need specific item types to have the durability attributes

#

i dont want to just slam it in Item and call it a day

#

im pretty much trying to access things from scripts that inherit from a specific script

#

in this case the Item

gaunt ice
#

is the type of item the base class Item? and the maxDurability is not a field belong to item, so cast it

languid spire
#

If you want to access the variable as class Item then it must be visible to class Item. End of story

tacit grotto
#

I want to make a delay function in a script, that is available in all other scripts, but WaitForSeconds() doesn't work.

    public void WaitFor(float delay)
    {
        StartCoroutine(DelayHelp(delay));
    }
    IEnumerator DelayHelp(float delay)
    {
        yield return new WaitForSeconds(delay);
    }

I call the function like this:

  GameScript.WaitFor(x);
gaunt ice
#

show your code

#

one line tells nothing

tacit grotto
#

it was a missclick

languid spire
gaunt ice
#

start coroutine will not stop following lines of code executes

#

startcoroutine is a non-blocking operation

gray arrow
tacit grotto
timber tide
#

What exactly are you using?

gray arrow
#

a huge rectangle covering the whole scene

timber tide
#

I mean the light revealing mask

gray arrow
#

for that it is a mesh

#

from a code monkey tutorial on YT

timber tide
#

I would keep that part of the script then, because that looked like it was working fine.

#

Curious what methods he's using

gray arrow
#

do you want me to post the important parts of the scripts here?

timber tide
#

What ever he's using to fill the mesh in

gray arrow
#
private void LateUpdate()
    {
        int rayCount = 300;
        float angleIncrease = fov / rayCount;
        float angle = startingAngle + (fov/2);

        Vector3[] vertices = new Vector3[rayCount + 1 + 1];
        Vector2[] uv = new Vector2[vertices.Length];
        int[] triangles = new int[rayCount * 3];

        vertices[0] = origin;

        int vertexIndex = 1;
        int triangleIndex = 0;
        for (int i = 0; i <= rayCount; i++)
        {
            Vector3 vertex;
            RaycastHit2D raycastHit2D = Physics2D.Raycast(origin, GetVectorFromAngle(angle), viewDistance, layerMask);

            if (raycastHit2D.collider == null) {
                // no hit
                vertex = origin + GetVectorFromAngle(angle) * viewDistance;
            } else {
                //hit Object
                vertex = raycastHit2D.point;
            }

            vertices[vertexIndex] = vertex;

            if (i > 0)
            {
            triangles[triangleIndex + 0] = 0;
            triangles[triangleIndex + 1] = vertexIndex - 1;
            triangles[triangleIndex + 2] = vertexIndex;

            triangleIndex += 3;
            }

            vertexIndex++;

            angle -= angleIncrease;
        }

        mesh.vertices = vertices;
        mesh.uv = uv;
        mesh.triangles = triangles;
        mesh.bounds = new Bounds(origin, Vector3.one * 1000f);
    }
#

thats the update function that draws the mesh

#

and then the mesh renderer just has a material which is kinda translucent

timber tide
#

Ah, pretty neat. It does skitter a bit on the edges but it does seem pretty good

gray arrow
#

so what do you think is causing the masking issue?

timber tide
#

I'm feeling like the script's not working unless I'm misunderstanding. He's changing the vertices, so it's not a rendering problem.

dry tendon
#

Heey, I need help @rich adder ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class NightBackground : MonoBehaviour
{
[SerializeField] private float latitude;
[SerializeField] private float longitude;

private string url = "https://api.sunrisesunset.io/json?";

private void Start()
{
    StartCoroutine(GetSunriseSunsetData());
}
IEnumerator GetSunriseSunsetData()
{
    string requestURL = url + "lat=" + latitude.ToString() + "&lng=" + longitude.ToString();

    UnityWebRequest www = UnityWebRequest.Get(requestURL);
    yield return www.SendWebRequest();

    if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
    {
        Debug.Log("Error: " + www.error);
    }
    else
    {
        // Procesa la respuesta JSON aquí
        string jsonResponse = www.downloadHandler.text;
        Debug.Log(jsonResponse);
    }
}

}```

#

Im trying to use that api

#

but unity send me this message

#

The fact is that the API works correctly cause when i paste this link into google :https://api.sunrisesunset.io/json?lat=40.4168&lng=-3.7038It correctly works and the API shows me this: { "results": { xxx }, "status": "OK" }

#

Does someone knows what's happenning?

rich adder
#

also dont dox yourself lol

#

hope thats a test long/lat

dry tendon
dry tendon
rich adder
#

hmm worked fine for me

dry tendon
#

thats the log

#

I think

rich adder
#

are you trying to run this through ADB?

#

or ur device

dry tendon
#

whaaat?

rich adder
#

it aint the script though because its working for me

rich adder
#

the red one

#

something to do with your adb

dry tendon
rich adder
#

is the tool between android n pc

#

Android Debug Bridge

#

or w.e

dry tendon
#

but it doesnt happen nothing

loud dragon
#

sorry for interuption but can anyone tell me a way so that i can use a a variable from another script so that when it changes in the original script it gets changed in the other also

rich adder
dry tendon
loud dragon
rich adder
loud dragon
#

in this i am taking count and points from 2nd script to the first one

dry tendon
loud dragon
#

but it is not showing changes while playing in the first one

rich adder
#

not needed tho

#

you just need to reference the Counter

loud dragon
#

yes

rich adder
#

store it inside a variable

#

you see how you do countincrement

loud dragon
#

yes

rich adder
#

pass a reference to Counter directly

#

so anytime you wanna do something to counter you have a working reference

loud dragon
#

can you write the command

sterile river
#

Quick question: I wanna freeze my Z position in 2D movement. I wanna do it by: The declaration is at the top of my class and the target transform in my update method

target.transform.position.z = 0.0f;```
rich adder
loud dragon
#

ok

rich adder
#

pass Counter as the type in the arguements of method

#
public void Init(Count counter)```
sterile river
loud dragon
#

will it take count from my other script?

rich adder
#
var bulletInstance = Instantiate(targetPrefab, spawnPos, spawnRotation);
            bulletInstance.Init(this);``` @loud dragon
loud dragon
#

ok

rich adder
#

and get rid of bullet_Destroy

#

change public GameObject targetPrefab;
to public Bullet_destroy targetPrefab;

loud dragon
#

I am keeping it there because it is checking at the time of collision

rich adder
#

but Bullet_destroy is literally the same object..

loud dragon
#

No they are different

#

Bullet prefab is the bullet gameobject that I am attaching it on inspector and bullet_destroy is reference to the script

gaunt ice
#

i think you need static variable or smth similar

rich adder
gaunt ice
#

the script will destroy itself...

rich adder
loud dragon
#

ok

#

Thanks

rich adder
#

public List <Bullet_destroy> bulletspawned

#
 if (bulletspawned.count < 5)
        { //etc..
shoot();```
```cs
        var newBullet = Instantiate(bulletPrefab, spwanPos, Quaternion.Euler(turn.y, turn.x, 0));
            newBullet.Init(this);
            bulletspawned.Add(newBullet);```
#

oh wait targetPrefab is not a bullet ? @loud dragon

#

my bad put it in shoot()

ruby python
#

!code

eternal falconBOT
#
Posting code

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

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

ruby python
#

Hi all,

I'm having such a weird brain fart moment. I'm trying to visual my raycast, but I can't seem to get my debug.draw to show up.

Debug.DrawRay(thrusterRayCastOrigin.transform.position, thrusterRayCastOrigin.transform.TransformDirection(-Vector3.up) * dustKicksRaycastDistance, Color.yellow);

Can anyone see anything I'm doing wrong please? 😦

gaunt ice
#

try to draw with a longer time instead of once frame, maybe 3 seconds

violet topaz
#

im having trouble adding bullet spread what is wrong ```cs
public class shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;

public Camera cam;

public float bulletForce = 20f;
private float timeBetweenShots = 0f;
public float fireRate = 15f;

//float scatterOffset = Random.Range(-10f, 10f);



public void Awake()
{
    cam = Camera.main;
}

// Update is called once per frame
void Update()
{
    if (Input.GetButton("Fire1") && Time.time >= timeBetweenShots)
    {
        timeBetweenShots = Time.time + 1f / fireRate;
        Shoot();
    }
}

void Shoot()
{
    GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
    bullet.transform.rotation *= Quaternion.Euler(0f, 0f, Random.Range(-10f, 10f));
    rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);


}

}```

gaunt ice
#

you should use bullet.transform.up (or right)

ruby python
#

X axis if it's side scrolling, Y if it's top-down.

ruby python
gaunt ice
ruby python
#

Ah thanks.

violet topaz
#

@ruby python like this cs bullet.transform.rotation *= Quaternion.Euler(Random.Range(-10f, 10f), Random.Range(-10f, 10f), 0f);

jolly cobalt
#
Debug.Log("Before AddListener");
var num = shopItems[i].id;
gmo.GetComponentInChildren<Button>().onClick.AddListener(new UnityAction(() => OnShopItemClick(num)));
Debug.Log("After AddListener");

any ideas why this doesn't add any listener to my onClick?

#

It passes through the code perfectly, but the button doesnt get a listener

ruby python
gaunt ice
#

does the buttons work?

violet topaz
gaunt ice
#

in my editor version it seems that it cant serialize action in the onclick list but it still works

analog yew
#

Hey, I use this code to teleport the enemy and the player at the start of each level. This works 90% of the time. However, sometimes either the Player, the enemy or both spawn at (0, 0, 0) with no error message at all. The teleportation debug is always true. The Player hast a CharacterController and the enemy a NavMeshAgent attached. I have turned AutoSyncTransforms on but it still doesnt work. I don't know what to do anymore

jolly cobalt
ruby python
# violet topaz top-down

Okay, take the random off the Y Axis. Being only side on you only want the bullet to vary up and down (x rotation axis). I will say that depending on what you're going for, 10 degrees either way is a lot.

violet topaz
#

@ruby python this rotate to bullet not the angle its going in

gaunt ice
#

you apply the same force at every bullet, so they just go to same destination (or same trajectory)

prisma blaze
#

if i want to just test some logic and not physics stuff, can i just use new with a monobehavior in nunit?

silver flicker
#

!code

eternal falconBOT
#
Posting code

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

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

silver flicker
#

Yo can anyone help me out here? I got these 2 balls - you can pick which one u want to use (coop type thing) And for some reason it doesn't let me ground check. atm IsGrounded() is constantly true whether you're above the range or not - IsGrounded() method at bottom https://gdl.space/gesefuguva.cs

summer stump
silver flicker
#

The idea is that the player can jump on eachother and that was the easiest solution i coul dput together

#

So I pass in the string of theother player's tag in the inspector

#

extremely hackish solution

summer stump
#

Oh ok. And is the the ground layer called "Jump"?

silver flicker
#

I've set the ground layer, the size of the square and the gizzmo and everything is fine

#

yeah the ground = jump layer

#

I gotta put in some headers

ruby python
open vine
#

Hey, does anyone know how to get the value of an enum? I have an enum in a scriptableObject and I'm trying to read what the value of it is so I have if (weapon.WeaponType == ?).

summer stump
silver flicker
#

Yeah they're different layer names

rich adder
silver flicker
open vine
rich adder
tulip tapir
#

Hi, i have again stubled over a Problem, that i cannot find in the Internet. I have an Audio Source in my Project where i play some Audio Files. It works in the Editor, it works in the Windows Build, but, it does not work on the Mac Build. The Video Player works normal everywhere, so, since the Video Player is also using an Audio Source, it is probably not related to some file type things. Does anyone has an Idea, what Mac wants?

silver flicker
tulip tapir
silver flicker
#

Yeah for sure

languid spire
tulip tapir
silver flicker
#

Check that out

summer stump
# silver flicker

Nothings jumping out at me, sorry. If you've got the layers all correct then that mask should be fine..

silver flicker
#

Alr Ill double check those layers

#

thanks anyway

tulip tapir
swift crag
#

This would be on the audio asset (the thing produced from the .mp3 in your Project window)

#

Not the audio source (the component you use to play an audio asset)

tulip tapir
#

i dont have an "asset", i have an mp3 file and an audio source

swift crag
#

find the audio clip in the Project browser and click on it

#

that is the AudioClip asset.

tulip tapir
#

ok, and then?

swift crag
#

Show us the inspector after selecting it.

rich adder
swift crag
#

Everything you see in the project window is an asset!

tulip tapir
swift crag
#

screenshot the entire editor window

tulip tapir
#

its just an mp3 file, nothing attachted to it

swift crag
#

That seems wrong.

rich adder
#

yea

violet topaz
swift crag
#

it must have an audio clip assigned to it (or have one given to it by your code)

tulip tapir
#

its given by code

rich adder
swift crag
tulip tapir
swift crag
#

loaded?

#

Are these MP3s in a StreamingAssets folder?

ruby python
tulip tapir
#

yea, i had to download an Audioloader because for some reason unity does not has that included

violet topaz
#
public class shooting : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;

    public Camera cam;

    public float bulletForce = 20f;
    private float timeBetweenShots = 0f;
    public float fireRate = 15f;
    public bool Auto;

    //float scatterOffset = Random.Range(-10f, 10f);



    public void Awake()
    {
        cam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButton("Fire1") && Time.time >= timeBetweenShots )
        {
            timeBetweenShots = Time.time + 1f / fireRate;
            Shoot();
        }
        //if (Input.GetButtonDown("Fire1")&& Auto == true)
        //{
        //    Shoot();
        //}


    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        firePoint.transform.rotation *= Quaternion.Euler(0f, 0f, Random.Range(-10f, 10f));
        rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);


    }
}```
tulip tapir
swift crag
languid spire
swift crag
#

perhaps your decoder is not working.

ruby python
#

!code

eternal falconBOT
#
Posting code

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

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

tulip tapir
swift crag
#

check if it's failing on there

swift crag
languid spire
#

and the Unity Editor obviously fails to recognise the file format

violet topaz
tulip tapir
swift crag
#

I don't know what third party audio decoder you're using.

#

You will need to check your logs and see if exceptions are being thrown.

tulip tapir
languid spire
#

It's simple it's not an mp3 file and you do not have the codec on mac to decode whatever it is

swift crag
#

or the importer is just failing to work, in general, on a mac

#

• Supports Windows, Android and iOS

languid spire
#

unlikely for something so simple as an mp3

swift crag
#

notably, macOS is not in that list

#

you may need to use another library to do the MP3 decoding. Once you have raw PCM data (a WAV file, basically), you can turn that into an AudioClip asset. I was helping someone with that here a month or two ago.

#

You should check your logs first, of course.

rich adder
#

Hmm interested to see how they made a working file picker..

swift crag
tulip tapir
swift crag
#

dunno how familiar you are with macs -- to open the library folder, open the "Go" menu in Finder while holding Option and pick "Library"

#

it's a hidden folder

ruby python
# violet topaz https://gdl.space/gijebihafu.cpp <@224097581494566914>

Okay, I think I know what's going on.

Change this.......

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

To......

GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaterion.Identity);

What I think is happening is that you're compounding rotations.

tulip tapir
swift crag
#

you can just search the log file for anything that looks relevant. it will not be hours of reading.

#

it may not be so simple to fix. If this package depends on a library that doesn't work on macOS, it will not be a one-liner fix.

rich adder
tulip tapir
# languid spire It's called learning

nah, i think its really just one line of code. for the video is was "Resources/Data" - that was the only difference in the path. probably there is somewhere in the loading script another apth like that

rich adder
#

not a true OS filepicker

#

dammit

swift crag
#

It does not sound like it does.

rich adder
#

smh why cant unity just call filepicker like it can for Editor class...

swift crag
#

the Resources folder holds assets that are imported and processed by Unity

#

It just lets you access the assets by name.

tulip tapir
swift crag
#

..what?

languid spire
tulip tapir
amber spruce
#

does a character controller component add a collider?

rich adder
languid spire
violet topaz
#

@ruby python same thing is happening just the bullet doesn't rotate to the shoot direction

swift crag
tulip tapir
languid spire
rich adder
#

they kinda dropped the ball on this one..

languid spire
#

amongst many, many other things

rich adder
#

yeah seems I'm slowly uncovering those things 😅

tulip tapir
languid spire
#

probably for copyright reasons

tulip tapir
languid spire
#

they would need to pay a licence fee to use copyrighted file formats that is why OS's have codecs

#

and why codecs are not universal

tulip tapir
#

and videos dont have that? o.O

ruby python
rich adder
languid spire
tulip tapir
rich adder
#

show us the Pivots in Local pivot mode @violet topaz

#

shoot point + bullet

rich adder
amber spruce
#

so all of my objects have a mesh collider but when i added a rigidbody to one of them they fell through the map

rich adder
#

pretty sure it gives u a warning in console for that

tulip tapir
rich adder
tulip tapir
tulip tapir
#

when i use the resources folder, it gets smashed into one file
thats why i use the streaming assets folder

violet topaz
#

@rich adder this?

rich adder
#

hmm why resource folder tho?

rich adder
#

and ur in center mode

tulip tapir
#

sry for caps, but i find it funny^^

rich adder
tulip tapir
#

but for streaming assets there is "of course" no Load Method^^

tulip tapir
rich adder
tulip tapir
rich adder
#

if you want to import custom tracks for user I suppose you can use Application.persistentDatapath

rich adder
#

you see the problem now right ?

#

but also change pivot from Center to Pivot (ik confusing names)

tulip tapir
tulip tapir
rich adder
#

and load As AudioClip

#

etc

swift crag
#

the problem is that the audio data needs to be decoded

#

if you import an audio file as an AudioClip, unity will decode it from whatever its source format is, then store it in a format it can understand

tulip tapir
violet topaz
rich adder
#

ig from there you can use the AudioClip import setting and change it to whatever

neat tinsel
#

I'm getting this error can someone help me please

rich adder
slender nymph
tulip tapir
ruby python
# violet topaz watch to the end thats when it happens

Oh, I think I might know what's happening. You need to reset your firing point rotation. everytime you fire, you're randomly rotating it. so for example, let's say that each time you fire, it randomly adds 10 degrees, over time it'll compound (ie. 10, 20, 30, 40, 50 etc. etc. etc.

tulip tapir
neat tinsel
slender nymph
ruby python
#

So, instead of just random. do 0+Random.Range etc. etc. (I think)

rich adder
tulip tapir
ruby python
tulip tapir
rich adder
barren vapor
#

If I want to load data from in an IEnumerator and wait until that's done, I can send a mail. Should I do it like this or how should I do it?

private IEnumerator NewMail(string _title, string _description, string _type)
    {
        yield return new WaitUntil(LoadUserData());
        //I'll put the script from sending the mail in here.
    }

public IEnumerator LoadUserData()
    {
        //Get the currently logged in user data
        Task<DataSnapshot> DBTask = DBreference.Child("users").Child(user.UserId).GetValueAsync();

        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
      //Loading the data below here...
    }
low perch
#

is there a reason why a variable would only be null in a method? I have it printing the correct value a variable should be assigned on void update but whenever a method is ran (it is called by ui button press), the variable is null.
The variable is only assigned by 1 line of code and I have it print whenever that line runs and it never sets it to null.
its also a unity transform if it matters

slender nymph
ruby python
violet topaz
rich adder
ruby python
#

You're spawning your bullet, then rotating the firing point and then propelling the bullet. Like I said, tired. lol.

tulip tapir
barren vapor
slender nymph
#

well you have to yield it still

#

yield return StartCoroutine(whatevercoroutine)

rich adder
tulip tapir
tulip tapir
rich adder
rich adder
#

if anything just blame unity for not having a proper built in File Picker for Player/Build

barren vapor
slender nymph
#

yes

tulip tapir
barren vapor
amber spruce
#

how do i fix the died part going beneath the you and have

slender nymph
rich adder
#

also not code question

amber spruce
#

oh sry

violet topaz
amber spruce
#

and thanks

barren vapor
# slender nymph yes

wait, doesn't yield return new WaitUntil(LoadUserData()); do the same as yield return StartCoroutine(LoadUserData())?

rich adder
#

also send a link of it, dont paste it inside the discord

violet topaz
barren vapor
ruby python
# violet topaz

Might be missing something, but shouldn't the *= just be = on the rotation? Looking at the numbers, the angles are getting compounded making it rotate way more than it should.

rich adder
slender nymph
barren vapor
rich adder
#

iirc StartCoroutine starts a new coroutine without waiting for current to finish

slender nymph
#

yielding it like that does work and waits for the new coroutine to complete before proceeding with the one it was started in

#

in this case, the spam generator is correct

rich adder
#

Ah ok , what does make difference when just writing yield return LoadUserData()

#

i normally just do that

barren vapor
low perch
rich adder
#

dont expect much from it

barren vapor
#

I have to attach it to the database yet

rich adder
#

if thats line throwing error

#

or destination_script

slender nymph
# rich adder so it is it working what sillybot said?

tbf they are getting clarification on something from the spam generator on something that was suggested to them in here. the yield return startcoroutine does work. i'm honestly not 100% sure the difference between that and just yielding the other method call though, but i assume it has something to do with how the coroutine will actually be handled by unity

rich adder
low perch
#

it prints next_location inside the method and it prints null also this is the error

Object reference not set to an instance of an object
game_manager.pressed_new_location```
rich adder
#

gonna see what forums say

rich adder
#

so next_location can be null but would not throw that line

#

you're trying to access something else that null

#

you can assign a null to something just fine as long as you don't try to use said thing

low perch
rich adder