#💻┃code-beginner
1 messages · Page 29 of 1
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I could be wrong but I think you wanna set Renderer.materials to your temp array once your done with it?
foreach (Renderer renderer in objectRenderers)
{
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
material.EnableKeyword("_EMISSION");
material.SetColor("_EmissionColor", color);
}
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
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
Anyone know how to make at the end of line 78 (https://gdl.space/joduxubava.cs)
!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.
get this info (https://gdl.space/puceqehuxe.cs)
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
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
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
It's not quite clear what you mean. Maybe upload a video demonstrating the issue.
also you can use a bin site to share large blocks of !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.
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Anyone know how to make at the end of line 78 (https://gdl.space/joduxubava.cs)
get this info (https://gdl.space/puceqehuxe.cs)
get what info?
What does "make at the end of line 78" mean?
it gives me the error
NullReferenceException: Object reference not set to an instance of an object
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
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)
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?
MeshData meshData = GetComponent<MeshData>();
meshdata is not a component
i am finding that out
again, do you not know how to create an instance of an object?
i guess not
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
the verticies array
what data do you think is in that array?
anyway i can set the spawned bullet's transform positions and rotation to another object's transform value?
you can pass a position and rotation to the Instantiate method
Vector3 and Ids are in that array
how?
vertices [vertexIndex] = vertexPosition;
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
your array does not exist. how can you be assigning anything at all to it if it does not exist
yeah ive just been monkeyseemonkeydo-ing tutorials i have to check on those thanks
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
what do you mean
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.
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
That is what i am here for
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
my only goal is to get the height of the mesh at a certain point and place a tree there
what version off c# and .net does unity 2023 use
thx
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)
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
i think ill try Mathf.Lerp because when i tried using Quaternion.Slerp i got my desired effect but
its kinda hard to explain
i'd bet the issue lies with how you get the desired rotation
hold on ill just send a video
im getting the desired rotation through the tracking of a transform object
i'd rather see your code
you see how it sorta like flips once it passes the middle threshold
as for the code here it is:
!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.
whoops
Quaternion rot = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direct), rotSpeed * Time.deltaTime);
rot.y = 0;
rot.x = 0;
yeah that's not right
i was following a tutorial for 3d smooth rotation and thought id just change the z value and set the rest to zero and call it a day
kinda lazy but it worked until well
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
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?
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?
reset Y velocity to 0 right before you apply the force to ensure it is consistent
update would be more performant compared to potentially starting a bunch of new coroutines quickly
any actual performance differences will be entirely based on implementation though
if you just want the desired Z rotation
tysm that worked, one other question, the commented code resulted in the player being unable to jump at all while the current code functions, why is that?
basically, i want the timer for the aggro to stop and reset if the player gets back into the enemy's range. I was reading up on coroutines and if i understand correctly, i want to call StartCorountine() when i leave the enemy's range, but if i get back into it, i call StopCoroutine()
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
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
if you normally move the player by assigning the velocity then you were likely overwriting the Y velocity each time you did so which of course would prevent the AddForce from being effective
You think im overthinking my code by using coroutines?
im just trying to get into the habit of writing optimized code
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.
Tbh, i'm preferring async over 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)
this is how i move the player, would this conflict with it?
i told you how im handling it... do you not have a definite answer for me?
no, that would not overwrite the velocity. if you comment out the middle line in your Jump method then uncomment the AddForce line it should theoretically work provided you are actually adding enough force
christ are you even reading what i've said?
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
ok, tysm 
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
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
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
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
Perhaps you just need this https://github.com/akbiggs/UnityTimer and all your timing needs are fixed.
very handy but im trying to stick to stock/built-on solutions for this project
Why?
it's supposed to be a "test" project, even tho i've been working on it for a year
idk i just want to
i don't wanna use outside libraries
Why?
don't reinvent the wheel if you don't have to.
gimme a quick second to gather myself
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.
I feel like it's a bit excessive for something that can be dealt with an if statement. 
okay
That's just me ig.
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
And if your game relies on many timings how many separate hard to debug and find if ststements you wanna write? Me personally as a rule I go if I use it more than ONCE it becomes a method and if I use it more than 5 times it needs to be it’s own class
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
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
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
also funny you bring this up, it's actually on the page's read me
in this Dev's opinion, it "hides away game logic"... whatever that means
but i guess it's a worry to someone
If we're talking about like that stuff, that can be fixed by other ways like breaking something down to multiple methods as necessary. That principle is true in any case anyways.
Feels like this library just kind of inlines the time handling. Personally, i think i can go well just fine without this.
Yeah kinda sorta same
I feel like spouting random crap at times. 
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

It’s okey. I suppose I was the same when I started. You will grow and learn
I will DEF use libraries for my "real" projects
libraries are gooood
so you're advice is not falling on deaf ears

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
The only library i used quite a bit is Unitask. 
Pretty much a library to make async work pretty well since i'm not using coroutines.
also very true
I'm planning to do this for my weapon system... As much as it can without any component involved so i can reuse it in other game engines.
Though, ams currently, not working on my game, just a discord bot that scrapes my school web.
making an audio player with "+ and - 5 second" buttons, getting this error despite clamping, anybody know a fix?
heya how do you make it so instantiated objects have suffixes like (1), (2), and so on
if multiples are spawned on every trigger
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?
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 🤷♂️
the framework's gun system fires ammo (which are actual game objects) in a certain order. i want to make the ammo at the bottom of the mag to be deleted first then to the top like it should be irl
why use names instead of an array or something?
but why would you need to append numbers to the names for that? or are you using GameObject.Find 
I think a list would be better in this situation unless im crazy
a Queue would probably be even better
i guess i wanted to replicate the prefab example that the framework had which had numbered ammo. the number-ordered ammo allowed ammo to be consumed from bottom to up (first one was original object then largest numbered object was at the bottom)
you shouldn't be relying on gameobject names for your logic. that will make it incredibly brittle
btw, anybody know somethin abt this?
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?
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
Most “best practices” are useful when working in a team. Solo devs can ignore most of them and keep in trucking
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
Well its slower
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 
Shader properties can be converted to ints statically
So can animator params for that matter
huh so im just retarted then
Mno you just never hit a scale where that matters
what scale we talking about
the name property is public. that means any object with a reference to it can change that property. what happens if you accidentally reference the wrong object and change its name? suddenly your code doesn't work and it's not entirely clear why
Performance or team wise
yea fair point ig cant argue
where it starts to be relevant to follow the good practices wise
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
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
this just as its states for performance u can store static string as well
still blindly hope u typed it in correct
Sure but unity does the hashing anyways
Well you could have a tool that reads out the animators properties and generates code for you. Ive been wanting to try out the new roslyn code this might be a fun weekend project
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
Nevermind its already done https://github.com/kayy/AnimatorAccess
damn this would be nice to have if my animators wouldnt be with like 2 animations at most 
man, more of these USELESS LIBS
nah im joking
this looks handy too
It is an old library I might fork it and give it an update
over engineered as fuck it must get pretty bad when u got a lot of animations for this to exist
I bet it will still work on modern unity, the animation api has not changed at all
It does
maybe you can clean it up, Uri
and make it not over engineered as Blin thinks it is
I wouldn’t call it over engineered. It seems to handle every case I can think of
ye
It gets so bad that we are heavily investing in creating our own motion matching tech so that we dont have to deal blend trees
What yall cooking gta 7? 
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
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?
Funny enough the gta6 leaks showed us that we are using the same publishedpaper for character locomotion step prediction l, since one of the debug tools show was taken straight out of the paper. Half life Alyx are using it too.
Do you need decimal points?
at early stages kinda? but at later stages the numbers are so high it wont matter
Can your money go negative?
no
Wel ulong is your best bet then
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
ulong is hundreds of magnitudes less than i need
Ah this is a cookie clicker type of game. i suppose BigInteger then yes
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?
Make an int variable called counter in a script.
Add a method called IncrementCounter() where you add 1 to the counter
Drag the object with that script into the button OnClick box
Select the method.
Done
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
The script with the counter should have a reference to the text, then inside that IncrementCounter method, you just do myTextReference.text = "Actions: " + counter;
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
dont worry i have TMPro on lol
ALRIGHT I GOT IT WORKING
thank you very much you are a massive help
guys, how can i make a script where if that gameobject is touched the players gravity gets switched
well first, don't crosspost
i accidentally posted it there and i realised there is a code-beginner channel
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?
well
then delete it from the other channel
👍
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
okay so then there are three steps you need to figure out how to accomplish:
- how to detect collisions
- how to change how gravity affects the player
- how to rotate the player
well this is what ive done so far
it's the same concept though. but instead of doing it when you press a key, you do it on a collision
use the CompareTag method when checking an object's tag rather than string equality
ok
but here you would just get the player's rigidbody2d and change its gravity scale as well as rotate it
so i'd need to do something like GetComponent(Rigidbody2D)
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
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.🥰
just use if statements in Update to delay your code. or use a coroutine. you won't be able to create a timer like that in a regular method
Thanks!
like how would i call getcomponent on the player and the object?
then wait
that doesn't mean you should post in an unrelated channel
well you're checking that the incoming collider has the "Player" tag, right? so if it does have that tag, then you know it is the player, right?
yep
so call GetComponent on the incoming collider if it has the Player tag
i think i got it
thanks
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();
}
start by checking that hit.collider is not null
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.
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...
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
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.
It can work by accident for some values but Euler angles are not unique so they're not reliable for this kind of thing
Okay, gotcha.
That works great, thank you. 🙂 Now just need to figure out why the thing won't close after it's open. lol.
https://hastebin.com/share/hidevavewo.csharp
https://hastebin.com/share/inuzuqiwav.csharp
In this i am getting null reference error
The object doesn't have a text component so CounterText is null
done but still same
What line is the null reference on?
done what?
Did you remove the line from Start that re-assigns it?
Yeah the start function tries to grab a text from the current gameobject. If that is null , then the text becomes null.
yes
Show what you have now
Have you assigned a bullet prefab?
What line is it breaking on?
Does it break on the "if" line or on the "Instantiate" line ?
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
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?
Probably need to inherit from Selectable https://docs.unity3d.com/2023.3/Documentation/Manual/script-Selectable.html
can anyone clear it
anyone
Not quite sure I understand what the count variable is for, or why it is in another class? The bullet_destroy script seems to be handling colision for each bullet too. Do you spawn more than one bullet_destroy script?
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?
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?
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
Make an initializer method
You would have to make a function then call it youself
so there's no default constructor?
idealy I would add parameters to the AddCompentent<Item>(...)
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);```
unfortunately you can’t do it that way
oh yes it is!! thank you
Well, there is. It's just a no parameter constructor that add component calls
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.
public void Create(ItemSO newItemSO)
{
Debug.Log(newItemSO.ItemSprite.GetType());
_image.sprite = newItemSO.ItemSprite; // This is line 25
}
Is there any way to detect sunset in real life and make something happen in the game?
anything is possible
yeah, sure, the fact is how
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
screenshot entire debug window not cutoff
its not
It's also possible that you call the function twice and either newItemSO or ItemSprite is null the second time it's called
Item newItem = newItemObject.AddComponent<Item>();
newItem.Create(monster.ItemDrop);```
Well, _image or newItemSO can be null
tryina see if _image wasnt set
can somebody tell what is wrong
xpSlider.Value = PlayerXp;
xpSlider.maxValue = PlayerNeededXp;
Your !ide should autocomplete so you don't make basic capitalisation issues
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.
Also errors should be underlined in red
_image is a private field of the class
I can see that, screenshot the script on this object
no bro, the inspector
The instance of the component in the inspector
it's not created because of this error
wut
you dont have this script on a gameobject?
The component with the Create function.
What's a good game to start off with I don't know any coding
this?
Flappy bird. Any tutorial pinned to this channel.
Ok
Item
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);```
Then how is _image ever set
it is null.
Preferably spawn a prefab that has it already set up
I think I can't work with prefabs since all items will have unique stats
that are generated when the item is created
You can set the values on the instance just fine
you already have a Create() method, pass the stuff there, ideally make it a Init() method
[SerializeField] isn't needed unless you did need the private field to show inside the inspector and want to assign it there
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?
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;
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?
defining != assigning
You declared it, thats good. But if you don't assign it, then it doesn't know where to point at..
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.
and what I'm trying to do is myFoo = "sprite";
and I know the "sprite" is not null?
since I debugged it
That would be fine.
But that is not what you are doing.
You are attempting to assign to the sprite property of an Image.
its not the sprite thats null mate
You must have an Image to be able to assign something to its sprite field
its the component of the image
so my gameobject doesn't have an image component?
its like saying "Come Do this work in my Kitchen at My House"
but you dont give someone the address to your house
public Image image;
public void GiveImage(Image theImage) {
image = theImage;
}
public void GiveSprite(Sprite theSprite) {
image.sprite = theSprite;
}
These are two very distinct situations.
You can look at it that way, but the gameobject is irrelevant to the code. You could add an image to that object and it would be meaningless if you never assigned it to the field
I do not understand anything you're saying 😦
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.
well I understand, but it doesn't make any sense to me*
You need to simply tell where your image component is through assignment =
the computer doesn't know
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.
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
one option is to do this in the inspector. you can drag an object with an Image on it into that field, or click the little circled dot and pick an Image from your scene.
When the code runs, that image field will not be null: it will hold a reference to the Image you picked.
they already have an Setup -like method they pass SO, all they need to do is pass the Image component as well
ah okaj I think I got it
newItem.Create(monster.ItemDrop);
Or just use a prefab and instance that instead of wholly creating it from scratch
That sounds like the most reasonable idea, yes.
at least it's working now, not sure if it's doing what I want though lol
Every item instance in your game will need an image
I'm guessing this some type of Image component in the scene already
Who knows lol
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
yes do that lol
Heey, is there any way to detect sunset in real life and make something happen in the game?
first thing that comes to mind: find a web service that can tell you when sunset is at a given location
^
The math probably isn't that hard, but there's just enough complexity with stuff like leap years, daylight savings time, leap seconds...
It’s fully explained here https://en.m.wikipedia.org/wiki/Sunrise_equation
All the date intricacies are solved by the DateTime class
looks a little frightening
yo can someone help with code here
you mean chat GPT give you shitty code? shocker lol
so you guys can't help?
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
help with what you havent explained the problem or code
ok bro so basically what I'm trying to do is basically a flag buidling
var rectTransform = (RectTransform)someComponentsObject.transform
never knew u can cast transform into rect one they are a bit different wtf 
its handy af
aaaa
Every GameObject must have a Transform. Any type compatible with Transform will work.
alright then will use that next time instead of GetComponent lmfao
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
You can also use GetComponent<Transform>(), incidentally
nothing special about RectTransform there
Transform is a kind of Component.
!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.
share your code correctly.
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.
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.
Don't do as
oh I put the brackets wrong. thank you again
The . operator has extremely high precedence. It goes before everything else.
is it Considered Harmful?
i guess you'll get null instead of an exception
It is slower, and you'd just trade out a cast exception for a null reference
which would be confusing the issue
so what are you expecting to happen & what happening instead?
how do i get a public static variable to show up in the inspecter
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
so are u saying cursorPosition is wrong?
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
come back to it with a fresh mind and start debugging your positions etc
👍 thanks again bro
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
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 🙂
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?
just call Instantiate when you get damaged
what
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
okay thank you
wdym Ontop of enemy
just dont make it child of enemy
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
when do you call Destroy() ? just call Instatiate there
I want to instantiate it on the position of the enemy and its not the child
this way spawned entity handler can handle what happens when you have a request for an entity to die
if I call instantiate after it, it doesnt work, if I do it before it will jsut get destroyed
show the code
whoa thats a good idea
do you see this
this is what happens when I do that
before you call Destroy, call Instantiate?
by instantiating it will get destroyed because its colliding with the enemy??
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
yah I really have to look into that
so fix that part
sounds like a good practice
I cant? it doesnt need a fix
thats how it is supposed to work
you clearly are not following, I just wanted to spawn something AFTER the enemy got destroyed
I get it..
Working with prefabs now 🙂
also I got it working now, @buoyant knot thank you so much
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
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
RotateTowards
@rich adder Ok, so, now i've got the API, but how can i ask for location permissions on android?
ubication permissions?
and how could i take latitude and longitude
sorry, location
hmm look into this maybe
https://docs.unity3d.com/ScriptReference/LocationService.Start.html
oh, thanks
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?
Modding is something we don't discuss here, see #📖┃code-of-conduct
Wait, decompiling and modding binaries?
I wasn't discussing that
Decompiling or modding altogether
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):
If you want to delve into URP render objects you can mask layers with stencils
yeah i tried that, thats why the entire screen is slightly greyscaled, but I couldnt get it to work so i resorted to maths.
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
what do you mean?
Basically what you're doing, but you'd obtain less popout effect
i still don't understand sorry
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
im trying to make them visible if they are in the line of sight yes
not spawning anything new
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
i am atking reference from one script to another but whne value is getting updated it is not showing on the other script
Help
i dont know exactly how to do that since the URP update
but i did try, like i said earlier the greyscale is a big mask
They are part of the URP render asset now instead of just individual components
very similar to built-in
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.
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
is the type of item the base class Item? and the maxDurability is not a field belong to item, so cast it
If you want to access the variable as class Item then it must be visible to class Item. End of story
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);
it was a missclick
That is not how Coroutines work
start coroutine will not stop following lines of code executes
startcoroutine is a non-blocking operation
update for you Mao:
i got the mask working and abandoned the other script entirely, but now I get this weird clipping issue with the mask, any idea why?
ok, thanks!
The mask you were using was something that I thought had down because it looked pretty good.
What exactly are you using?
a huge rectangle covering the whole scene
I mean the light revealing mask
I would keep that part of the script then, because that looked like it was working fine.
Curious what methods he's using
do you want me to post the important parts of the scripts here?
What ever he's using to fill the mesh in
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
Ah, pretty neat. It does skitter a bit on the edges but it does seem pretty good
so what do you think is causing the masking issue?
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.
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?
debug.log your requestURL
also dont dox yourself lol
hope thats a test long/lat
hehe, true
Ok, one moment
whaaat?
it aint the script though because its working for me
whats that
oh, it appears me when i dont conect my pc with unity remote 5
but it doesnt happen nothing
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
are you testing this script in editor mode ?
no, just in play mode
A property / event could help
No I mean inside the Unity editor or you are trying to run it on the phone?
in this i am taking count and points from 2nd script to the first one
nono, just inside unity editor
but it is not showing changes while playing in the first one
ideally an event
not needed tho
you just need to reference the Counter
yes
yes
pass a reference to Counter directly
so anytime you wanna do something to counter you have a working reference
can you write the command
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;```
make an Init method and call it from your coutner when you spawn bullet
ok
pass Counter as the type in the arguements of method
public void Init(Count counter)```
It gives me an error and says: "The return value of Transform.position is not a variable and therefore cannot be changed"
will it take count from my other script?
any idea?
var bulletInstance = Instantiate(targetPrefab, spawnPos, spawnRotation);
bulletInstance.Init(this);``` @loud dragon
ok
also dont keep count inside the bullet
and get rid of bullet_Destroy
change public GameObject targetPrefab;
to public Bullet_destroy targetPrefab;
I am keeping it there because it is checking at the time of collision
but Bullet_destroy is literally the same object..
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
i think you need static variable or smth similar
you dont need the gameobject, bullet_destrory already has that
the script will destroy itself...
the spawned amount should just be held inside a list
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()
!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.
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? 😦
try to draw with a longer time instead of once frame, maybe 3 seconds
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);
}
}```
you should use bullet.transform.up (or right)
Looks like you're rotating around the Z axis (forward), so the bullet is spinning along it's length, try adding the random to the X or Y axis instead. It's 2D so you should use the Z axis at all.
X axis if it's side scrolling, Y if it's top-down.
Not sure what you mean.
method declaration https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html
public static void DrawRay(Vector3 start, Vector3 dir, Color color = Color.white, float duration = 0.0f, bool depthTest = true);
Ah thanks.
@ruby python like this cs bullet.transform.rotation *= Quaternion.Euler(Random.Range(-10f, 10f), Random.Range(-10f, 10f), 0f);
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
is your game side or topdown ?
does the buttons work?
top-down
in my editor version it seems that it cant serialize action in the onclick list but it still works
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
yep
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.
@ruby python this rotate to bullet not the angle its going in
you apply the same force at every bullet, so they just go to same destination (or same trajectory)
if i want to just test some logic and not physics stuff, can i just use new with a monobehavior in nunit?
!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.
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
What is up with that layermask you're passing in?
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
Oh ok. And is the the ground layer called "Jump"?
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
Ah okay, same should apply though in terms of the axis to use.
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 == ?).
Ok, so the two balls have DIFFERENT layer names? I was thinking it is sensing its own collider
just cast it to an int
Yeah they're different layer names
oh you mean weapon.WeaponType == WeaponType.Shotgun
So what I've done is I've removed the jump layer entirely and the player can still infinitely jump so ik its not that
Yep ty both of those work, just wondering is there any pros or cons on each one or is it just preference?
yeah use enum , only use ints if you need specifically something else with ints and need it, but otherwise defeats the point of an enum
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?
Gotcha ty
What file type is your current file
mp3, or mp4 for Video, that works fine
I think Mac can play mp3, right?
Yeah for sure
If you have the correct codec installed. Do you?
im not really into audio stuff, i dont know what a codec is^^, but it works in the editor and on windows. Do you suggest, that Mac is missing a Driver?
Check that out
Nothings jumping out at me, sorry. If you've got the layers all correct then that mask should be fine..
hm, im not sure if that helps, some of the things mentioned are not visible in my Audio Source in the Editor
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)
o.O
i dont have an "asset", i have an mp3 file and an audio source
find the audio clip in the Project browser and click on it
that is the AudioClip asset.
ok, and then?
Show us the inspector after selecting it.
audio file is an asset mate
Everything you see in the project window is an asset!
there is nothing in it
screenshot the entire editor window
That seems wrong.
yea
i got it but after shooting for a little it does this @ruby python
What does your audio source look like?
it must have an audio clip assigned to it (or have one given to it by your code)
its given by code
show code & show your pivots
and how does the code know about the audio clip? is it stored in a field somewhere?
it gets loaded
Can you show code again please?
yea, i had to download an Audioloader because for some reason unity does not has that included
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);
}
}```
yes
ah, so you're decoding the audio at runtime and playing it..
not an mp3 file. Just because something has the extension .mp3 does not make it an mp3 file
perhaps your decoder is not working.
!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.
but its working in the editor and in the windows build
but it's not working in the mac build
check if it's failing on there
any files in a StreamingAssets folder get imported as "default assets", since they aren't actually processed by unity
and the Unity Editor obviously fails to recognise the file format
https://gdl.space/gijebihafu.cpp @ruby python
well, i already checked on mac, thats why i know its not working. but i wanna know why.
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.
It's simple it's not an mp3 file and you do not have the codec on mac to decode whatever it is
or the importer is just failing to work, in general, on a mac
• Supports Windows, Android and iOS
unlikely for something so simple as an mp3
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.
Hmm interested to see how they made a working file picker..
(for the record, this is a very important piece of information to lead with)
iver never worked with logs yet, how do i do that?
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
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.
sound like hours of reading for 1 line of code, cant i just fix the missing thing in the loading script?
It's called learning
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.
and ofc seems to be a custom UI for file directory command..
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
That "AudioImporter" asset also does video?
It does not sound like it does.
smh why cant unity just call filepicker like it can for Editor class...
this is a completely different situation if it's coming from Resources
the Resources folder holds assets that are imported and processed by Unity
It just lets you access the assets by name.
no, for the video you can work with url, and depending on windows or mac you need to change that line of code
..what?
platform agnostic, wont work
its not, its just called like this on mac
does a character controller component add a collider?
its weird becausee they make it work if you use the Editor class but not for Player / Build.. sucks
CharacterController has it's own special collider
@ruby python same thing is happening just the bullet doesn't rotate to the shoot direction
oh, you're talking about where StreamingAssets is located
but i know, its super annoying^^
agreed. Unity dev's special brand of stupidity
they kinda dropped the ball on this one..
amongst many, many other things
yeah seems I'm slowly uncovering those things 😅
i still cant believe that unity does not has a simple audio loader. they have it for video, why not for audio? xD
probably for copyright reasons
o.O?
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
and videos dont have that? o.O
Take out the random for the moment and see what happens.
also you never did share what I asked..
some do, some dont
anyway, i found this one now
https://docs.unity3d.com/ScriptReference/AudioImporter.html
would that work?
like Clip = AudioImporter(path);
I think this just changes the settings via code, the ones you normally see on an Audioclip's import inspector in asset folder
so all of my objects have a mesh collider but when i added a rigidbody to one of them they fell through the map
thats because mesh collider and rigidbody don't mix unless its convex
pretty sure it gives u a warning in console for that
alright, i guess mac users are just fuck"d then^^
no code, no game. Windows wins again :/
I'm not entirely sure what exactly you're trying to do and why you need that asset specifically? I kinda skimmed thru ur post
i want to load an mp3 file, that is not scrambled when building, into an audiosource to play it in the program
wdym scrambled
when i use the resources folder, it gets smashed into one file
thats why i use the streaming assets folder
@rich adder this?
hmm why resource folder tho?
i had this before, because, for the resource folder, there IS ACTUALLY a recourses.Load Method xD
sry for caps, but i find it funny^^
true but I meant, why using ResourceFolder in the first place instead of having the files in the project folder
but for streaming assets there is "of course" no Load Method^^
u mean just making a custom folder? dont custom folders also get scrambled?
just inside any folder in the project? what reason you dont want "Scambled" or part of the build files
i need to access those files after the build, move things in and out later
if you want to import custom tracks for user I suppose you can use Application.persistentDatapath
this?
we're getting close
you see the problem now right ?
but also change pivot from Center to Pivot (ik confusing names)
is that a Method that actually laods? if yes, how? or it this just the Path, because i know the Path, i just need the Method
i tried it, all folders get fused together when building
only streaming assets remain
You can probably use HTTP request into that application.persistentdatapath folder
and load As AudioClip
etc
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
if that is the case, then wouldnt it also be the case for video? which works totally fine just with the url?
watch to the end thats when it happens
ah, that might work.
ig from there you can use the AudioClip import setting and change it to whatever
this gives you some preloading options already
https://docs.unity3d.com/ScriptReference/Networking.DownloadHandlerAudioClip.html
I'm getting this error can someone help me please
whats cocoapods
this doesn't look like an issue with your code
would that work?
like skipping all the other stuff, and just using the method?
why would yu skip that lol
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.
i just want to
clip = Load(Path, mp3);
Play();
xD
i'm trying to use ios for AR but whenever i load the scene this pops up and not able to install cocoapods. which is the right thread i should post this in?
#🔎┃find-a-channel to find a relevant channel.
how would i reset it
So, instead of just random. do 0+Random.Range etc. etc. (I think)
Thats pretty much what that does
cause, with Video it works just like that^^
Clip.url = Path;
Play();
easy peasy^^
thanks
That might be wrong actually, sorry, very tired and brain isn't working properly.
so i can skip that other stuff and just use 2 lines of code?
make your Load method return the AudioFile
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...
}
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
you can yield a StartCoroutine call
Actually, just try moving your rotation line below the addforce line.
it didn't work but i will just wait for @rich adder to help me
huh ? did you fix the pivots first
You're spawning your bullet, then rotating the firing point and then propelling the bullet. Like I said, tired. lol.
o.O
meh, i mean, thanks alot for the help, i might try using that later, but for now, i have to hold my deadline, and i think im just gonna say, mac sucks and doesnt work^^
later ill fix it maybe for mac
So like this?
private IEnumerator NewMail(string _title, string _description, string _type)
{
StartCoroutine(LoadUserData());
//I'll put the script from sending the mail in here.
}
...
lol don't see how this is a mac/ os issue 🤷♂️
well, mac is the only system where its not working already^^
but true, actually its a unity issue
you're blaming os for using a third party asset which you probably don't need lol
hmm, yea maybe
if anything just blame unity for not having a proper built in File Picker for Player/Build
ah thnx. Never went deep into coroutines. The yield makes the script (the comment part IEnumerator newMail) wait until it's done?
yes
yea, better
if something doesnt work, i have to blame someone^^
and i cant blame myself^^
Thank you!
how do i fix the died part going beneath the you and have
make the text mesh width wider
also not code question
oh sry
@rich adder
and thanks
wait, doesn't yield return new WaitUntil(LoadUserData()); do the same as yield return StartCoroutine(LoadUserData())?
ok whats the current script
also send a link of it, dont paste it inside the discord
have you tried it to see?
no, I have a large script. It uses both.
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.
try firePoint.transform.rotation *=
aslo GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firepoint.rotation);
why don't you test it out and find out for yourself if it works the way you expect it to
well, I got a quick answer
iirc StartCoroutine starts a new coroutine without waiting for current to finish
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
Ah ok , what does make difference when just writing yield return LoadUserData()
i normally just do that
That's what I want. I basicly start a IEnumerator to send a mail, but I first wanna check the current number of all mails sent, so I can update it in the database
next_location only returns null in a specific method, everywhere else like update etc returns it as valid
https://pastebin.com/PyF5W9U2
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
so it is it working what sillybot said?
dont expect much from it
I'm changing the script rn. I'll test it in a few minutes.
I have to attach it to the database yet
its probably target thats null
if thats line throwing error
or destination_script
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
ahh ok , good enuf thank you 🙂
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```
gonna see what forums say
= null this would not throw error
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
here we go, i found a decent explanation of the difference: https://forum.unity.com/threads/why-cant-you-yield-an-ienumerator-directly-in-a-coroutine.359316/#post-8812777
it's being assinged to the target of the destination in the unity a* pathfinding project
Ah exactly what i needed , thanks!