#š»ācode-beginner
1 messages Ā· Page 220 of 1
i have the space for it and i dont think any firewalls are blocking it
imma restart my computer real quick
I was trying to make a script that spawns enemies, and the spawned enemies get a script that modifies their behaviour for a bit and is then removed, but only if the enemy is spawned via said spawner, so I don't want to have the prefab with the script itself
okay so then read past the first sentence
It should work if I attach the scipt later right? I am thinking if I should just make it part of the general enemy behaviour instead, but not sure
surely you bothered to read the entire first message i replied with
I did, but I was hopping for more precise response than "probably doesn't, but dunno"
Alrigth, lets see if it does...
the time it took for you to type that message, you could have easily just tested it yourself like i suggested you do
Hey, is there a way to switch from using the update function to fixed update function? To give you some context, I have this script that is mainly focused on movement and a bunch of calculations to make that movement happend (like acceleration, decelleration, etc.). When I realized that it would be better to use fixed update in the long run and tried to change that, my player makes no moment at all and I don't want to have to change each and every variable because that would waste too much time. So is there an easier way to simplify this prosses?
also at no point did i say "probably doesn't" nor did i imply that. in fact, i implied that it should work
how would just switching from Update to FixedUpdate be better in the long run? you use FixedUpdate for anything that needs to operate on a fixed timestep, like physics, and Update for anything that needs to happen each frame, like getting input
To switch, just rename the method from Update to FixedUpdate.š¤·āāļø
does know what I should do if it says "the system cannot find the file specified" in the assetbuilder?
I am very new to unity so idk what to do
Where/when does it say that?
oh well I heard that you can run into a problem with update that it can run much differently on slower and faster computers depending on the game that is being played
ik I did that but but I had a lot of problems to get the player to move just as I programmed it in the update function
Update is called every frame. so it runs at exactly the framerate. provided you are correctly making things framerate independent you will not run into issues
you also haven't shown relevant code so we couldn't possibly know what isn't working, but i'd guess that you are probably attempting to get input in FixedUpdate which is typically a no-no
Of course. There are things that should be in fixed update and there are things that should be in update. For example input querying would often fail in fixed update.
ok, so this is a strech but does anyone want to help me with my game? im not quite sure how to make a map.
ohh I see, well thank you
!collab š
also not a code question
We do not accept job or collab posts on discord.
Please use the forums:
⢠Commercial Job Seeking
⢠Commercial Job Offering
⢠Non Commercial Collaboration
Nowhere on this server
The links above go to the forums
trying to make a lethal company map for the first time, I can send the exact error msg if you want
i wasnt asking if someone wanted to join my development
i was asking for help
That counts as collaboration
There is a noncommercial collab link
kinda hard to help without the error message, no?
Moving Temp/unitystream.unity3d to C:/Users/astud/Downloads/LethalSDK_Project/Assets/AssetBundles/testingshit.lem: The system cannot find the file specified.
Always do send the exact error message. That being said, if it's modding we can't really help you, both because it depends heavily on the original project and because it's a prohibited topic on the server.
i wasnt
apologies, here's the error for ya'll
you specifically asked if anyone wanted to help with your game. that is not asking for help with figuring out how to do something, that is asking for collaboration.
if you need help with something specific then use id:browse to find the most relevant channel and ask an actual question there https://dontasktoask.com
you probably worded it wrong. do you have any issues or errors with your code? that's what this channel is for . . .
oh mb
Then try being clearer. You asked if someone could help with your project instead of asking a question
So we assumed it wasn't a specific question
you arte right i wrote that weird. i feel bad asking for help with stuff like this because i know very little. to clarify, does anyone know how to make a map
Can't really help with that much. It sounds like something specific to the game sdk. You'll need to ask in the game(moding) community. You probably just miss some kind of file.
youre* right
Ok, well not really a code question on tbat case.
You can try in #ā°ļøāterrain-3d
Or go to the #š ļøāprobuilder
Or try in the !blender server
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
Those are the main ways to make maps
this doesn't sound like a code question, and "map" could mean many things. it seems like you want to build or design it in 3D. that would be a different channel or with a 3D program . . .
ok thanks
i just had the perfect name for this variable and then forgot it
whats a better name for a variable that manages how long it takes friction to change? frictionChangeTime
yes, its in 3d
does anyone know how to make a map
is not a very clear question. you have provided no details, you've clearly not bothered looking for any sort of tutorial or documentation related to whatever kind of map you want (and you haven't even bothered specifying whether you mean scenery in a 3d game, a 2d tile based map, etc)
im makins a fps
There are many ways to make a map. Try looking for some tutorials or, better, going through the courses on unity !learn.
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
I usually use the words duration or timer, duration being for how long itll take and timer for how long it's currently taken if I am tracking it manually
dynamicFriction, frictionDuration . . .
the word just suddenly went out of my head
conversion, transition . . .
bro this stuff still aint downloading
ive clicked retry so many times, restarted my computer so many times, and check if anythings blocking it, and its still not downloading
have you done anything to anger Bill Gates?
probably
did you click the link at all?
try buying another windows key
will chill him out
anyways, does someone know how to make drag for the player not to slide like a penguin everywhere?
yes but it aint helping
my player accelerates to a target velocity proportinal to controller input
keep it like that
if controller input is zero, it accelerates to zero
mine is keyboard input...
makes no difference
ok, how tho?
||can i copy??||
my player movment script is super complicated. you do not want to copy it
just the part about the speed i said, i'll try to adapt it
and also
my friends write stuff so bad, it looks like hierogliphs, i can read it
calculate:
target velocity is a function of move input.
delta velocity is a function of target velocity - current velocity, acceleration constant, and delta time
iām not at home anyway rn
ok, i'll try, thanks
and I say you donāt want to copy because i have a bunch of geometry and shit for slopes, and interface for my own custom physics engine
oh, nice
idk i might share later. it is well documented enough that you might get something out of it
Hi there! I'm new and I'm wondering how to create blinking led textures? like leds on a terminal panel for example? What technique do you use to achieve this? Thanks!
depends, generate a nice pulsing pattern then switch material to on/off
i use a mix of images and lights..
ok so multiple texture interpolation? right?
emissive materials
yeah exactly Emissve Material for on, and a non-emissive / kinda blacked out version of same texture
just using numbers I do it sure
I use perlin noise for my flickering lights for example
okay thanks, I'll look into it
still needs work to sync light component with material.
edit Removed gif dont wanna trigger someones eyes lol
Ok... so I am trying to add the script that replaces the mats of the meshrenderer temporarilly to the spawned enemy, but it needs to be on the gameobject that actually has the meshrenderer, which is not the top one, also some enemies even have more than one meshrenederer. How can I get those? Something like TryGetComponentsInChildren doesn't exist rigth?
GetComponentsInChildren
@buoyant knot any ideas in how to jump? the method im using is not working
oh, forgot you're not at home, my bad
why cant i edit sprite shape profile its all just grayed out
Yes, the awake() does trigger if anyone was curious; just that it does nothing cause the paramaters are not setted up, the component is added with no values whatsoever. Guess I will have to refactor it to account for that
yes, that's how it works if you are just using AddComponent because that does not allow you to assign anything to the serialized fields in the inspector beforehand
if you want to assign things in the inspector you would need to instantiate a prefab instead of using AddComponent
this does not appear to be a code question
I though that if I added a script it would use the default values of the script in the assets, not the default parameters of the parameters itself such as "0" or "none"
that is editor only
set rb velocity directly. write new Y velocity.
Calculate the new y velocity using a kinematic equation, using desired jump height and gravitational acceleration
this y vel should be a constant
The thing now is the renderer might be a normal MeshRenderer or a SkinnedMeshRenderer, that's why was seeking for something like TryGetComponentsInChildren instead of just getting them directly. How do I do this?
specifically:
vf^2= vi^2 + 2ad
vf = 0, because that is y vel at top of jump arc.
d = desired jump height.
a = gravitational acceleration, which should be rb.gravityScale * Physics.gravity.y
and vi is the y velocity for your jump (which needs to get written to rigidbody velocity)
which is the initial y vel you need so that you reach exactly that jump height under exactly that gravity
understand?
no, but kinda yes
no need to explain further, imma make effort to understand
i don't want to take much of your time
a lot of people are lazy fucks, and define jump force based on some bullshit number they just move up and down
that kinematic eqn gives you exactly the number you need to jump a specific height
yo can anyone help help remove this outline over my floors n stuff
im using an enemy ai and those r the boundaries but idk how to remove them visually
wait nvm
how do i reference a vector on void update on a completely different method in the same script?
that was exactly what i was going to do
lol
im still doing it though
you can choose to use math to make your life easier, or struggle with a longer grind. itās ultimately your choice.
ill struggle thank you
im trying to jump too
im using charactercontroller tho
that is apparently the only issue i have everywhere
now for the parkour movementation and tricks
(i'll go bald due to stress from doing the animations and coding)
help, shows i cant convert vector3 into float, i thought velocity.y was a vector
wait
velocity's just a vector that shows where i'm going
try what i sent
dude im copying you
did it work?
oh
you canāt just assign the y component of vel. you need to assign a whole vector
velocity.y is already a vector, vector 3, and it's public so the void can definitely reach it
i'm following brackeys' tutorial on fps movement but he doesnt show jumping
thats basically it
im trying to just modify the y part of the velocity vector to get it
fixed it
apparently i was assigning a whole vector to just the y part of the vel. vector
i just needed to get rid of the .y in velocity.y
void Jump(float jumpParam)
{
if (isGrounded && Input.GetButtonDown("Jump"))
{
velocity = new Vector3(velocity.x, jumpParam, velocity.z);
}
}```
the if statement's wrong btw
the if statement goes on the void update
nice
the xyz independent values of vector3 are read only which is why you can't assign to them directly
ok
void Jump(float jumpParam)
{
velocity = new Vector3(velocity.x, jumpParam, velocity.z);
}```
so the thing doesnt jump for some reason
im going to try putting absurdly high values on jumpParam
nasa wants to know your location
still doesnt work
there's like character controller templates by unity you can start a project with
what
and just rip those apart to see how they do the logic
i did not know
idk man i wanna do it by myself
im technically not even doing it by myself and i know it
no one is
yeah
that's fine, but ideally you should be reading up on a guide because cc isn't beginner friendly
yeah i will now
⦠no
no?
velocity is a Vector3
that is what i said
velocity.y is a float
nowadays is like car companies
same thing, different badges
iām literally telling you not to try to assign velocity.y
assign a whole new Vector3 to velocity
this velocity is not going to work because you didnāt actually assign it to a rigidbody or character controller
in essence, you did nothing
that is what i did
what why
that is not what you did here
you wrote a vector3 to some variable you call velocity
which is not the same as assigning a velocity to your rigidbody.velocity (or character controller)
ok
you could rename that variable boogerAIDS, and it wouldnāt change how your code functions at all
how do i assign it to charactercontroller?
i donāt have experience with character controller, so you need to look at its actual methods to see how to tell it to move
ok, last question of the day (or not)
how do i make UI?
Like... just right click on the jerarquy UI > whatever you want to add?
If I do this, the out of the TryGetComponent is setting the parameter above with the same name or just creating a local variable?

What's the syntax of a variable declaration?
Guys, would anyone know how I add ammunition to my gun without it exceeding its maximum capacity? like in half life 2/gmod private void OnCollisionEnter(Collision collision) { if (collision.collider.CompareTag("SmallAmmoBox") && gunHolder.GetComponent<Gun>()) { Gun gun = gunHolder.GetComponent<Gun>(); if (gun.currentAmmo < gun.maxAmmo) { int maxAmmoToAdd = Mathf.RoundToInt(gun.maxAmmo % 25); int ammoToAdd = Mathf.Min(maxAmmoToAdd, gun.currentAmmo); gun.AddAmmo(ammoToAdd); Destroy(collision.collider.gameObject); } } }
public void AddAmmo(int ammoAmount)
{
int ammoReload = (int)(maxAmmo * ammoAmount);
currentAmmo += ammoReload;
ammoText.text = currentAmmo.ToString();
ammoText.text = currentAmmo.ToString();
}
Like... type + name + value ? I don't get the question
Type identifier
To be precise. Declaration is always creating a new variable. Does that answer your question?
Shouldn't that result on two variables of the same name and prevent me from doing it?
if (currentAmmo > maxAmmo)
currentAmmo = maxAmmo
Not if they have different scopes. The previous variable is of class scope. The new one is local
Can I set it to the class parameter then?
Sure, just don't declare a new variableš¤·āāļø
Oh I see, I though that was needed
Only if you declare a new variable.
!code
š Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if(Input.GetKey(KeyCode.W))
{
Animation.Play();
}```
is this good for a basic walking animation?
like extra simple but not the best
does it work?
You need some extra logic.... but thats something ppl do just play animations via code
If u want it to be simple thats fine
That's what you should tell us. Does it work?
ima try it rn
That literally just plays the animation when you press W, literally anything else, you probably want an animator controller, even if it is a very basic one
I know godot programmers do it like this
i mean if it works
They check all of there animating logic via code instead of the Animator
I mean, you can, I have done it, it is just way harder to coordinate more complex animations
it'S more like an rpg
so the only thing i should concentrate is the cam
Its a top down RPG? like the old school zeldas?
3d game
Oh....
I still recomend using and animator, specially cause I am assuming you have different sprite animations for each WASD right?
4 direction animation
ye
but the character is not that complex
If its 3D you should definitely use the Animator
well i guess i will use animator then
So lets say you have a walking animation that transitions to a Run Animation if u start running it will just jump to the running animation making it look very jank lol
I thought u were making a simple 2D platformer
Watch a tut
I mean the transitions the animator mades up are still kinda janky sometimes anyways
The animator system is way to complex to go over in a code channel
They look jank but without the smoothing it will look EXTREMELY jank
void OnCollisionEnter(Collision2D collision)
{
if (collision.gameObject == player)
{
Debug.Log("Collision!");
}
}
I've been learning Unity 3D for the past month but I decided to try Unity 2D for once.
The problem according to VS Code is that OnCollisionEnter() is unused
But with Unity 3D, OnCollisionEnter() usually functions as a standalone method that doesn't need to be called
What's the difference? How do I detect 2D collisions if not this way?
Just a round up for the very basic, create an empty state as the entry, make a variable for each of the axis movements (you can do float or bools), make it so you can transition from any state to any other with no exit time with the condition corresponding to that animation, I am assuming this is what you want to do on a basic 2d rpg
Hes making a 3D RPG. But those ideas still apply
OnCollisionEnter2D() instead
If it is 3D he probalby just needs one animation and rotate que playerObject in the direction they are moving
I agree
How do i write a mesh to a Skinned Mesh?
I have a small test script that displaces the vertices of a mesh (one of the examples from the mesh API documentation). On a regular mesh with a mesh filter it works fine. But on a mesh with a Skinned Mesh Renderer, it does nothing. What's the proper way to change the vertex positions of a skinned mesh per frame?
You'll probably need a custom shader that takes account of your desired vertex displacement when applying bone matrices to the mesh vertices.
Thanks. Do you mean do the vertex position changes in the vertex shader instead? I can't just change them with a C# script?
so i can just make animation with state machine in animator right?
Yep. For skinned meshes vertices are displaced in the vertex shader to apply the animation.
So any changes you do are not effective, or might cause unpredictable results if actually forced.
I literally just did something similar and just tried to find a MeshRenderer and a SkinnedMeshRenderer and just used exactly the same code accounting for a MeshRenderer and a SkinnedMeshRenderer with (if meshRenderer/skinnedMeshRederer != null) {whatever you want to call from the renderer here}
oh huh, but this shader isn't part of the material you use on them?
I personally have not used an state machine yet, never needed one, but I guess you could
Ahhh, hmm. So the deformation caused by the rig is calculated in the vertex shader, or just applied there? I'm trying to adapt some stuff from Blender where all deforms are applied to the mesh independent of any shader. So it is possible to get the deformed position and then modify it before anything renders.
the goal is to compare the base position of the mesh and the deformed position after the rig, and then add some amount to the deformed position.
that's interesting that it does default to vertex shader cause I can imagine how intensive animation is otherwise
this is a state machine right?
Thats a state
Animator is the whole state machine
ok thx
Might be wrong, but afaik, animation is stored as deltas to position/rotation. The animation system creates a transformation matrix for each bone and passes it to the shader. The shader then transforms the vertex position according to that matrix and vertex bone weighs. You could modify the bone to affect all the bound vertices on the CPU side, but if you want precise control over each vertex, you'll probably need to do it in the shader.
I might be wrong, but the state machine isn't like an special type of state that swaps between several states?
i just wanted to know so i wouldn't be wrong
Fsm is a pattern
Blender does a lot of stuff on CPU that game engines do on GPU, since performance is not an issue. That or it has more advanced shader compilation system, again mainly due to differences between 3d modeling software and a game engines. Game engines are often focused on performance and less on asset creation/modification.
My code is using meshfilter to access the mesh's vertices. There doesn't seem to be an equivalent on skinned mshes.
{
Mesh mesh = GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
Vector3[] normals = mesh.normals;
for (var i = 0; i < vertices.Length; i++)
{
vertices[i] += normals[i] * 0.001f * Mathf.Sin(Time.time);
}
mesh.vertices = vertices;
}```
Yeah. That makes sense.
You should cache the mesh in awake
Skinned renderers don't use the mesh filter. You could try using the mesh stored on the skinned renderer itself, but again, I'm not sure it would work correctly:
https://docs.unity3d.com/ScriptReference/SkinnedMeshRenderer-sharedMesh.html
I've tried that and can't get it to do anything either š¦
So it sounds like if I want to do mesh operations on a skinned character, it needs to be in the vertex shader. I'll look more into that, thanks!
Theres no reference to a animator
ye
If the displacements you want to perform are predetermined, you could use blend shapes too.
i am gonna add it
How do you call a method in general..?š
Oh my god i didnt even realize that
What's the correct syntax?

Should probably go through C# basics first before continuing
if you still wanna know:
// Calling a Method in Unity C#
void MyMethod() // This can be named anything you want as long as the name's unique
{
Debug.Log("Welcome to my method!") // This just displays a new message in the Console
}
void Start() // This could be any Unity method: Start, Update, FixedUpdate, LateUpdate, etc.
{
MyMethod(); // Runs the method whenever the greater method runs (Here, it would activate at game start)
}
// Without annotations
void MyMethod()
{
Debug.Log("Welcome to my method!")
}
void Start()
{
MyMethod();
}
they are not asking for help.....
oh well š¤·āāļø
Im trying to make a airline sim game and am currently working on perfecting my arcade flight physics. The code is quite messed up and i have spent probably 5 hours on it now just trying to find fixes to all of the bugs i come across. Let me know what you think, im looking for feedback.
Heres the code: https://paste.ofcode.org/7gYHkKsKbua33JfnUWPq5B
Thanks!
I was trying to point Goldwerdz to a solution as well as to test their understanding of the basics with that question.
oh well š¤·āāļø
Anybody know why the function isn't being called?
There are no errors so I dont really know where to look
Coroutines should be started with StartCoroutine
Which you can't do from another class afaik
It worked 1 time like this and I don't remember changing anything
So you should make an intermediary method that callse StartCoroutine
I still dont understand why this is a coroutine at all
if ur trying to wait until the File is done being read that shouldnt be a coroutine
ReadPixels() can only be called at the end of a frame after everything has rendered
It worked once lol, it screenshot the screen and saved a png file.
Now the function isnt being called at all
I think the actual contents of the function is fine because I haven't changed it
And because I directly copied it since I had no idea how texture stuff worked
The Yield Return is whats messing it up
what ienumerator actually is
You have to call StartCoroutine()
is there an article for that because Ive never heard of it
And the Unity website always gives a huge scary block of code as the example
ienumerator is state machine
and each yield return creates a new state
btw i am not the one who write c# compiler so i maybe wrong, better ask in c# discord
!code
š Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Could I call it from LateUpdate() without having to yield return?
I was thinking LateUpdate() could work but idk if thats EndOfFrame
just start coroutine......
StartCorutine() Will for sure work tho
So what
StartCoroutine(thumbnailmanager.GetThumbnail())?
because I dont understand
Yes
oih
Thank you it works
But i dont understand why xd
What did StartCoroutine() Do that calling it normally didn't
I would watch the link he sent
Could prolly better explain than any of us
LateUpdate is before all rendering
https://docs.unity3d.com/Manual/ExecutionOrder.html
This is giving me trouble, im storing the music and sfx audio levels in playerPrefs, when I reload the scene sfx gets reset to 1
private void Load()
{
musicSlider.value = PlayerPrefs.GetFloat("music");
sfxSlider.value = PlayerPrefs.GetFloat("sfx");
}
but when I swap those 2 lines of code the opposite happens
music gets reset to 1
you're probably doing things in their onValueChanged event. use SetValueWithoutNotify instead
this is using sliders, is that a slider setting or am I missing something
it's a method
why cant i make player object collide with enemy object and it destroy player object
i tried everystep i dont know where did i made mistake
!code
see #854851968446365696 for what to include when asking for help because that is certainly not enough context to know what your issue is
Yeah, I dont think I understand how to incorporate this, the documentation doesnt have examples
could I send the script so you can maybe explain how to use it
you call that method instead of assigning to the value property
public void ChangeMusic()
{
Debug.Log("ChangeMusic");
mixer.SetFloat("MusicVolume", Mathf.Log10(musicSlider.value) * 20);
Save();
}
that method is 100% irrelevant to what i suggested
you do it here.
oh ok I thought it was used in the other function
why
the method's name literally starts with "SetValue". I suggested you use that after having only seen you assign to the value property.
ok yes thank you, that worked
issues with debug mode bump
i have a problem with XR. in the first scene my XR origins hands move properley, but when i switch the scene the hands don't move
Still need help?
How can it be that this outputs 1? Am I am misunderstanding Mathf.Lerp?
!code
š Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Show the whole thing please š
yes
What other code do you need on this? It's in an OnTriggerStay2D() function.
Maybe because your t is 7?
Or does this mean the 7 will be clamped down to a 1 anyway
this is a unique issue that only started happening recently, mainly i just want to use the debugger to find values
Ah, so I misunderstood Lerp. Thanks.
also, altering the for loop to be that minus one doesnt seem to fix it
Well, you're lerping the interpolation value between 0 and 10 where your current interpolation value is 7 (between 0 and 1, 7 is beyond the max which produces the max value).
So 10/10 is stored into the variable and prints 1.
ok i fixed it (i was using 3d script in 2d project)
i did find that i is always 0-8 and j is always 0-1
specifically when pixel density is 2, anyway for that reason
i goes to 12 and j to 2 when pixel density is 3
Where is the UV array defined?
The fit being thrown was about index out of range so one of your arrays isn't the size of i
What was the Unity Editor error?
StyleBoxProcedural.GenCorner (UnityEngine.Vector2 pos, UnityEngine.Vector2 stretch_factor, System.Single corner_radius, System.Boolean outline, System.Single border_start, System.Single border_end) (at Assets/CatUI/Theming/StyleBoxProcedural.cs:72)
StyleBoxProcedural.UpdateMesh (UnityEngine.Rect rect) (at Assets/CatUI/Theming/StyleBoxProcedural.cs:118)
StyleBox.Render (CatUI.Drawing.Drawer drawer, UnityEngine.Rect rect) (at Assets/CatUI/Theming/StyleBox.cs:21)
UIElement.DrawStyleBox (StyleBox box, System.Nullable`1[T] rect) (at Assets/CatUI/UIElement.cs:68)
UIElement.DrawStyleBox (System.String id, System.Nullable`1[T] rect) (at Assets/CatUI/UIElement.cs:73)
CButton.Update () (at Assets/CatUI/CButton.cs:21)
The error may be elsewhere - I'm not aware of the initial problem.
I dont think its that
one sec making a code paster
Assuming we were shown random code not related to the problem
I think its somewhere else
The method you showed isnt the method unity is complaining about
they abandoned it and basically told me to suck it up and document it myself
and im trying to figure out how to increase pixel density
so far not working
drawing.cs
stylebox.cs
Its just this one class
catui.uielement
Where is CButton?
does anyone have a good color theme for an alien planet
ah one sec
This is the coding channel, perhaps try asking in #š»āunity-talk
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[AddComponentMenu("CatUI/Button")]
[DisallowMultipleComponent]
[ExecuteAlways]
public class CButton : SelectableElement
{
public override string Category => "button";
// Update is called once per frame
protected override void Update()
{
base.Update();
if (mouseDown) {
DrawStyleBox("pressed");
} else if (hovered) {
DrawStyleBox("hover");
} else
{
DrawStyleBox("normal");
}
if (focused)
{
DrawStyleBox("focused");
}
FinalizeDraw();
}
}
Im guessing it has something to do with this i honestly cant even read 90% of the code tho
vertices[((i * 4) + j)] = new Vector3(vertex.x, vertex.y, 0);
On line 72
im hoping to rewrite into something more legible
first i gotta even understand where it begins
Well the error message says the index goes out of range when u call the method on line 118 inside of the StyleBoxProcedural Class
The only time u access an array is on line 72
Things to be concerned about - these are relative to the size and values of i.
I was looking at that to but i cant even comment on it because i have no idea what he was trying to accomplish
There doesn't seem to be any early escape patterns so if i is anything more than vertex count when multiplied by 4, the line will throw an index out of range.
i got it to render, a little anyway
corners dont at all but
it doesnt immediately explode
Whats the point of all the code?
The dirty solution would be to set the delimiter to i * 4 + pixelDensity < vertex_count - without not knowing what the code is supposed to do..
this was my dirty solution for the time being lol
Tisk tisk
its a bit broken
Again why all the code tho?
the border color is now inside
to make a procedurally generated ui element so you can scale without losing quality
the gencorner does as the name implies, generates the pixels for a corner
is used 8 times, 4 for the outside border and 4 for the inside corner
Didnt look like it
I typed Destroy and it was green and not yellow
It extends from monobehaviour im guessing
Call it with the class
https://docs.unity3d.com/ScriptReference/Object.Destroy.html
how would I adjust this background image to dynamically fit the height of the text?
As far as I know, the text can overflow but its height remains unchanged
this is a scripting problem, is it not
if you wanted to do it through code, tmp has stuff like its desired height from the text
but should be possible through just existing ui
I don't think it's possible through the UI, when I searched online there was a variety of scripting solutions in combination with components that didn't quite work for me https://stackoverflow.com/questions/46019256/unity-ui-textbox-dynamic-height-how-do-i-make-it-expand-based-on-text-amount
#321235, #543159, #421262
yo wait that acc looks sick what
the last purple is def the best
tyty
the first answer uses the content size fitter, which really should be fine for this. though the ui channel is still probably more relevant.
tmpro has some values you could use, but the content size fitter would be doing the same thing
hit enter too early on that first message
// Clone the prefab
if (currentIslands.Contains(i + 1))
{
islandImage = Instantiate(greenIslandPrefab, islandPosition, Quaternion.identity);
}
else
{
islandImage = Instantiate(islandPrefab, islandPosition, Quaternion.identity);
}
// Edit the on click function of the button
Button button = islandImage.GetComponent<Button>();
button.onClick.RemoveAllListeners();
button.onClick.AddListener(() => IslandClickedEvent(i));
I'm not sure why this isn't working.
I have a function that generates islands in my game, and the "Clone prefab" part does what it says, it uses my greenIslandPrefab and islandPrefab to make a copy, then my problem arrives.
The on click changing doesn't seem to work and I don't know why.
I added a debug statemet checking if button isn't null, and no debug log shows, so button isn't null, so I don't understand why it wont work. The listener's aren't cleared, and no new listener is added
(islandImage is defined outside of the if statement, so islandImage in Button button = islandImage.GetComponent<Button>(); isn't the problem
Also yes, the cloned game objects DO have a button property
Hi Guys i have some finalization Problems with my Flappy Bird Project from Zigorous.
Im All the Way to the UI Part and i want to implement my ScoreText into my GameManager.
- using UnityEngine.UI; <- is in the GameManager , also Created as an UI - Text (Text Mesh Pro) (Old Guide from 3 Years ago uses just Text.
Small Changes i did apart from the Original Video was that i couldnt just drag my Font as usual into the Space , i had to Create a Font over Window - TextMeshPro - Font Creator. Dragged the github into it and only did a 1024 x 1024 size and created it.
Beside that i followed all Steps from Guide but the Game Manager wont allow me to pull it in as a Text , it Marks it as a GameObject and only allows me to put it as one.
I tried a bit around but dont Understand why my Text isnt applied as it.
Picture Shows my GameManager , My Score Text Settings , maybe someone knows why Unity shows it as a GameObject...
whats indicating to you that the listeners arent cleared? if you debug anywhere between those statements, and you dont have any errors, then all non persistent listeners should be removed.
Maybe it is affecting the wrong button, or maybe your game isnt registering a button press at all. Could be the case if you dont have an event system in your scene
That Text your using is not the TextMeshPro component.
It's Unity's legacy text element.
Because Text is a different component. A different Type. You need to declare your variable as a textmesh pro text if you want to be able to drag the tmp text in there.
would using.TMPro help ? or do i need to create a LegacyText ?
The TextMeshPro one exists in the namespace using TMPro and the type is TMP_Text.
Using just allows you to use the types from that namespace in your script. Nothing more. You still need to declare the variable correctly.
you should be able to slot it in then
The video shows that both my load and create island functions are called in start (depending on if a save file is found), then I show when the game runs, in the console log it says islands have been loaded because a save file was found. And you can see islands being created, as clones as their prefabs, but the button property isn't changed at all.
Even with button.onClick.RemoveAllListeners(); the buttons all still have the same on click property. And I just can't figure out why, because the buttons are being created correctly, their names are changed using the islandImage game object, their positions are changed, etc after I attempt to edit their button properties.
now it should work right ?
did you upload the wrong video?
Try it and see.š¤·āāļø
Did , yea i found a work around to implement the old github legacy text , but didnt change the declaration, thanks !
Dont bother with that old Text.
It's Legacy for a reason.
Programmers didn't slave away in the SDF mines for years only for people to not use them š
those are persistent listeners, not affected by RemoveAllListeners
on an unrelated note, am I the only one who highly dislikes the somewhat common approach of calling RemoveAllListeners before adding a listener?
ohhhhhh
Well that complicates things.
Is there any way to do what I need?
I'm trying to attach my islandClickedEvent function to the buttons when they're created, which the buttons number (i) so when the buttons are pressed they trigger islandClickedEvent and input the islands int i
If you don't want multiple subscribers, why not use a simple delegate then?@pallid nymph
exactly my point
I've never thought that was a common approach. Never encountered it in someone's code.
should be fine to just do what you're doing through code and remove the pre-existing listener on the prefab
Good, good, so perhaps it's just my luck. I've seen it in questions here and there, as well as in code at work. š¤·āāļø Always makes me a little sad.
If you mean remove this part, I've removed it but my issue still persists, because it still doesn't add the listener I need. Idk what I'm doing wrong, or if I'm just not understanding.. XD
š¤·āāļø its the equivalent (mostly) of setting a delegate to null. not really sure what else you could even do if you wanted to re-use a button for example.
stuff you add wont appear there, those are just for setting up stuff in editor time
Well, there's a singular RemoveListener, and generally whoever adds a listener should manage when they want to remove it as well. I'm not an extremist, so I wouldn't say there are no decent use-cases for it... just fewer than it is used in š (from what I've seen)
Oh.. wow that's weird.
Well my issue is fixed then XD
Thank you!
Welcome to game dev. Sanity not included.
yea id suggest adding a debug just to make sure the whole thing works still. It definitely isnt intuitive but sounds like there wasnt an issue to begin with. Anyways if this is from a prefab, you dont even need to call RemoveAllListeners because it wont have any
Yeah I'm definitely going to need debug logs XD
Because now the function is called each time a button is clicked, meaning the listener was added correctly, but the int I tried attaching isn't correct
im assuming this is the closure issue, although i didnt exactly see the relevant code let me check one second
// Edit the on click function of the button
Button button = islandImage.GetComponent<Button>();
button.onClick.RemoveAllListeners();
button.onClick.AddListener(() => IslandClickedEvent(i));
I checked the first button, which at that point, i equals 0. But it returns 42 XD
store i in its own variable and then use that variable, let me find a link which explains it
Is this in some sort of loop?
The lambda will only catch the final value of i
https://unity.huh.how/anonymous-methods-and-closures
there we go, vertx had a link onit
Yes, it was a loop, part of a loop actually
And redeclaring the variable worked! Thank you!
Now time to run into 50 other issues, or well, knowing the scope of my game, 4569206 š
I definitely dont regret getting into coding lol
I just realized, It's 3AM 0_0
Good night... I don't have a problem
German here , 10 AM š
i just made a game with the help of GMTK's video and ive learnt a lot and i want to make a 2d platformer right now would it be a good idea to start now or should i make some more small games?
What does this game look like?
its a flappy bird rip off
Hey guys, im trying to create a 2d side scrolling shooter. Looking for some help with collision. I have a script for my spaceship to fire a bulletprefab. However I cant seem to get the bullet to destroy any object. When I play the game I can visually see collision but nothing is registered in my console log (except for the fact that my bullet is colliding with itself somehow).
{
Debug.Log("Collision detected with object tagged as: " + collision.gameObject.tag);
// Check if the collided object is not tagged as "Player" and it's not a bullet
if (!collision.gameObject.CompareTag("Player") && !collision.gameObject.CompareTag("Bullet"))
{
// Destroy the collided object
Debug.Log("Bullet collided with: " + collision.gameObject.name);
Destroy(collision.gameObject);
}
}
}```
I would say then that it depends on the scope of what you want to make.
If it's a simple 2D platformer ala Super Mario Bros, go for it.
If it's a full on metroidvania like Hollow Knight... probably want to get more practice in >_>
mario with some mechanics like ddashing
I'm not sure I agree with the implication that Super Mario is simple... but okay š
Generally, I think the trickiest part about a platformer is the character controller... one can make a simple one, buuut the more features you want ot add, the more and more tricky it'll become
I'm saying like, original Mario Bros. Realistically you can create levels pretty quickly with Tilemaps.
Obviously you can go nutty with the character controller.
But I assume this guy isnt.
yeah, so that's going to be very difficult
yes that's quite a bit more complicated
I mean, I think it'll be a good learning experience.
State management, physics, etc.
But it's definitely a few steps up from flappy bird.
should i learn through tutorials while making the gaame?
like ill maake the game through tutorials but learn as well
I need help to fix this error im having after updating my project
!code'
š Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://gdl.space/mudiliqihu.cs i am having this issue in jumping can any one tell me why and how to fix it
any pointer in the right direction would be appriciated
do a ground check or collision check
is it possible?
i am doing a double jump
i have a ground check layer setup for movement
simple way is then make a variable int timesJumped = 2; each time you jump timesJumped--; and each time you try to jump check if(timesJumped >= 1) when you collide with the ground reset timesJumped = 2;
I mean that's up to you, no?
some thing like this>? sorry for my messy code
if your second if is the collide check then dont need to make a nested if
You'd probably want the jump counter to be a class variable if you aren't wanting it to reset every frame
otherwise if you jump only once you wontr be able to jump 2 times next since you only reseting if the counter is 0
Hey guys, for the past few days I've been trying to make a dash for my game but I can't manage to make it consistent.
Firstly it seems that its framerate dependent because I'm not always getting the same distances, and I don't know how to approach this.
Secondly, for some reason I can't manage to make the dash go where the player is exactly looking with the camera, like if there is some delay
Maybe some of you guys can help me a bit, I'll appreciate it a lot. This is all the code that involves dashing
public void OnDash(InputAction.CallbackContext context)
{
if (context.started) dashTriggered = context.ReadValueAsButton();
if (context.canceled) dashTriggered = context.ReadValueAsButton();
if (context.started && !grounded) dashPerformed++;
}
private void Update()
{
Dash();
}
private void Dash()
{
if (grounded)
{
dashPerformed = 0;
dashing = false;
}
if (dashTriggered && !grounded)
{
if (dashPerformed <= maxDashes)
{
performDash = true;
}
}
if (performDash)
{
dashing = true;
Vector3 moveDir = transform.InverseTransformDirection(cam.transform.forward) * dashDistance;
Vector3 targetDashAmount = moveDir;
dashAmount = Vector3.SmoothDamp(dashAmount, targetDashAmount, ref smoothMoveVelocity, 0.15f);
Vector3.ClampMagnitude(dashAmount, maxForce);
StartCoroutine(PerformDash());
Invoke(nameof(ResetDash), dashDuration);
}
}
IEnumerator PerformDash()
{
float startTime = Time.time;
grav.gravForce = 0f;
while (Time.time < startTime + dashTime)
{
transform.Translate(dashAmount * Time.deltaTime);
//Invoke(nameof(DelayedDash), 0.025f);
yield return null;
}
}
private void ResetDash()
{
dashing = false;
grav.gravForce = gravForce;
performDash = false;
dashTriggered = false;
}```
^ or use a bool
how to do that'
it is still giving me the same problem with the jump counter
i started coding just yesterday , i just copied those errors into chat gpt and asked it what the problem is before coming here š 99% of time it fixed my problems š
it gave me 25 more errors dw
These errors are unrelated to your code, maybe you just need to try deleting the library folder and let unity remake it. Im not sure of an exact fix, but dont listen to advice about using chatgpt because this isnt your code so you cannot even modify it in the first place.
lmao
Are data that are changed during runtime saved when it is on a scriptable object?
Like, when i stop then play again, will the value be retained?
No
In the editor they may save because you are directly modifying the asset. In a build it will not work
Didnt tested but should work. Make a trigger collider for the ground tho or use oncollisonenter2d instead.
[SerializeField] private int jumpCount = 0;
[SerializeField] private bool canJump = true;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && canJump && jumpCount < 2)
{
DoTheJump();
}
if (jumpCount >= 2)
{
canJump = false;
}
}
void DoTheJump()
{
jumpCount++;
// do the jump code here, apply your velocity
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Ground"))
{
jumpCount = 0;
canJump = true;
}
}
thanks
A lot of this seems weird, like what's the purpose of that whole smoothdamp part? It may be the cause of getting different distances on different framerates.
You should debug though what the actual distance is, or just what values are along the way.
Save to a file, depends what you're saving really or what you consider a large amount. Json is pretty commonly used except if you're loading a LOT then maybe you'll want a database of some sort
Aight thanks
the smoothdamp is to give the player somee sort of momentum
Did you debug what values it was returning ever? Now that I look even closer at this, I believe you may either be running many coroutines, or be using smoothdamp in a wrong way
If it is starting many coroutines, then itd be making one per frame which explains the distance issue you mentioned
nope, I'm debugging them rn, I'll tell you what i find
I do have to go so wont be able to help further. Add debugs too for when the coroutine starts, so you can see how many it starts. Also you can probably just use MoveTowards instead of smoothdamp but dont know if thatll really matter here
private void Dash()
{
Vector3 dashDir = transform.InverseTransformDirection(cam.transform.forward);
Vector3 targetDashAmount = dashDir;
dashAmount = Vector3.SmoothDamp(dashAmount, targetDashAmount, ref smoothDashVelocity, 0.15f);
Vector3.ClampMagnitude(dashAmount, maxForce);
Debug.Log(dashAmount.magnitude);
if (grounded)
{
dashPerformed = 0;
dashing = false;
}
if (dashTriggered && !grounded)
{
if (dashPerformed <= maxDashes)
{
performDash = true;
}
}
if (performDash)
{
dashing = true;
/*Vector3 moveDir = new Vector3();
moveDir = transform.InverseTransformDirection(cam.transform.forward) * move.y + transform.InverseTransformDirection(cam.transform.right) * move.x;
if (move.magnitude == 0f)
moveDir = transform.InverseTransformDirection(cam.transform.forward);
moveDir = moveDir.normalized * dashDistance;*/
StartCoroutine(PerformDash());
Invoke(nameof(ResetDash), dashDuration);
}
}```
I took outside the loop the vector calculation so it is performed every frame, and now the debug shows me that dashAmount is some what around 0.8 and 1
every time I move the cursor it changes and then the value increases until it reaches 1
no worries thx
I am trying to make a animation play when walking the character. It worked for pressing W, but when i added that it should play it too, when S is pressed it only worked for S. I found a solution but why didnt it work.
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
direction = transform.rotation = Quaternion.Euler(0, 0, 0);
anim.SetBool("isWalking2", true);
}
else
{
anim.SetBool("isWalking2", false);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
direction = transform.rotation = Quaternion.Euler(0, 180, 0);
anim.SetBool("isWalking2", true);
}
else
{
anim.SetBool("isWalking2", false);
}```
it worked with this
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))
{
anim.SetBool("isWalking2", true);
} else
{
anim.SetBool("isWalking2", false);
}```
theres a button and i want to change it to everytime clickable one
i want to make some blood decals but first i need to know if i can place my decals or not so i shoot a ray (blue color) from impact point to where the bullet (yellow ray) originally goes. why is it not detecting the wall? (it's tagged correctly and the enemy collider should be ignored)
public void ShootRayOnImpact(Vector3 impactPoint, Vector3 direction)
{
Debug.DrawRay(impactPoint, direction * 10, Color.blue, 3f);
RaycastHit blueRayHit;
if (Physics.Raycast(impactPoint, direction * 10.0f, out blueRayHit, ~ignorme))
{
if (blueRayHit.collider.gameObject.CompareTag("FS/CON"))
{
Debug.Log("blood splash reached the wall so you can spawn decals");
}
}
}
this is where from it gets the input: hit.transform.GetComponentInParent<bloodSplat>().ShootRayOnImpact(hit.point, fwd);
if i debug Debug.Log(blueRayHit.collider.gameObject.name); nothing appears on the console.
edit: even if i don't use layermask still nothing on console.
i fixed the issue there was some problem with my badly implemented coyote timer i removed it i wil need to find a better way to implment it
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
Hi. I have a problem: I have an action in void Start, and it only works 1 time in the entire time (as it should be), but I need that if the object is active, then void Start works again on 1 frame. I have an object running, void Start works, but if I turn off the object and turn it on again, void Start will no longer work. How do I make void Start work every time I turn on an object 1 time per frame?
why not just use update
use onenable
and it is called as method no void, void is return type
and if you hope it runs every frame, use update
It's like this, so that this action is done with each frame
update runs each frame
then use update
If I put Start() in void Update, then the action in void Start will be done every frame when the object is active. I need the action to be done only 1 time if the object is turned on. Optimization
use OnEnable if you want something to happen each time the gameobject is set active
ok
"How do I make void Start work every time I turn on an object 1 time per frame?"
Im getting mixed messages here
yeah, the wording is off
!code
š Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Why my player isn't jumping?
https://paste.ofcode.org/39vjMa8GLkmqhADpZQ4tBxW
The Move function works just fine
ur jump adds force but ur Move Function manually overriding the y velocity..
so when u jump it might increase just a very very small fraction.. and then the move function uses that fraction and sets it to be that each frame..
it wont continually go up
so how can i do it? 'Cause if i set that to 0, its also a problem
u should instead
- when ur jumping using a bool so it does a different thing
- also when you start the jump zero out any forces on the y
you need gravity
wait its a rigidbody.. why do u need to set its y velocity?
idk, i put it there cause i cannot ovveride the x and z alone
or at least, idk how to do that in another way
so basically, i need a bool, set the bool to true when jumping and put the rigidbody y velocity to 0, then put the velocity of the rigidbody to the gravity of the project?
yea a bool should straighten it up
// Zero out y velocity to prevent unwanted vertical movement
if (!_isJumping)
{
_rb.velocity = new Vector3(_rb.velocity.x, 0, _rb.velocity.z);
}```
void Jump()
{
// Make Player Jump
if (!_isJumping)
{
_rb.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
_isJumping = true;
}
}```
something similar to this..
im sure u can figure it out
k thanks
what is the value of the first dropdown option? is it 1 or 0?
If possible can anyone help me understand what ive done wrong please Assets\Scripts\SettingsMenu.cs(380,33): error CS0103: The name 'coinBeds2sDropdown' does not exist in the current context https://i.imgur.com/EtWDXlh.png
show where you declare coinBeds2sDropdown
and !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
if it helps i can share the file as i dont understand
ok i did that one but now have Assets\Scripts\SettingsMenu.cs(383,17): error CS0111: Type 'SettingsMenu' already defines a member called 'ChangecoinBeds2' with the same parameter types https://i.imgur.com/Tdgg0BG.png
It states you have two methods of the same name with the same parameter types. The parameters must be different. Did you change them? If so, make sure you saved the file . . .
yes ive just renamed them again and saved and still have the same errorAssets\Scripts\SettingsMenu.cs(383,17): error CS0111: Type 'SettingsMenu' already defines a member called 'ChangecBeds2' with the same parameter types
and that name cBeds2 is not used for anything else but what i wanna use it for
i can share file if it help understand
Check or send the script. You have two methods with the same name for SettingsMenu . . .
Also, did you clear the previous error from the console?
!code
š Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yes i cleared the error
You have 3 definitions for ChangecBeds2 in the class
sorry i dont understand
i coped what was already there for another item and renamed what i need
What part do you not understand?
Someone know how to save the Inventory?
How many overloads do you have for that method? Check and make sure each (method) signature does not have the same parameters . . .
I cant to use PlayerPrefs
Using JSON or binary format. There should be a few tuts to look at to get started . . .
tysm
Do you happen to have a tutorial video?
sorry im new to this and have issues understanding anything im doing . I had a dev who did all this but he is no longer doing any more game dev work so im having to try and work out what im doing.
so i copied one thing for example public TextMeshProUGUI showCoinDoorImagesLoc; and changed the CoinDoor to cBeds2 public TextMeshProUGUI showcBeds2ImagesLoc; and everything that had CoinDoor on i had also copied it and replaced the same CoinDoor with cBeds2 so everything should be right
Those have nothing to do with the error
Hi, does anyone know aht do i do after I donwload this git file ?https://github.com/jamschutz/Unity-Standard-Assets
I wanna import the old standard assets into my unity
these assets
!code
š Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Share the code diamond
We're talking about the method ChangecBeds2. Do you know what a method is?
i dont have any code related problems to share, perhaps i should ask on #šāart-asset-workflow ?
That's not how you share the script. Use the links provided below with !code . . .
š Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
U need ti build it
copy/paste
I was talking to diamond not u yodaarc
oh, gotcha
Oh, then go asset > import costum package
Sorry for the confusion
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
sorry, do I ask for help here?
If it is about code then yes
Lines 333 and 383 are identical
You can't define a method with the same name and parameters twice
You can make methods with the same name only if parameters are different
I forgot to put name sorry I mistyped
Your application wouldn't know which method to call at runtime.
Thank you for the help that made more sense i appreciate the help
Ok so this is the custom package. Can I just drag drop it somehow in a way that my cursor doesn't cancel out?
( Please Ignore the unfathomably sexy pictures of Leon kennedy )
why doesnt it let me drag drop the assets here for example ?
that is a Folder, what does it contain?
it's just a folder of folders of folders ... of more folders
why not drag/drop in FileExplorer?
Wdym? It's already in fileExplorer, I just wanna import all this folder-inception into unity gang
is it possible to physically push open doors without a rigidbody attached to the door itself?
man, seriously, move it to your project folder using File Explorer
oh i see what you mean
yes, as long as the one doing the pushing also has a collider
would i do it with raycasts?
no
how would i go about doing it then?
attach a collider to both the door and whatever is doing the pushing
yeah ive got all that
oh, ive got a seperate script for controlling rotation for my door so i dont actually have a hinge component on it
if thats what your thinking ive got
I am presuming you know how to open a door, yes
yeah
question, say for example i have this skill slots that can be activated whenever I click on it. What's the best method when I want to auto activate it without clicking whenever the skill is not on cooldown?
Ok so I pasted the entire folder into packages of my current Unity project.... I named it Babuska. It's in the file_explorer and everything but it's not visible on unity 
A door without hinges is a Wall
why?
nono it does have a hinge the hinge is a parent empty game object of the door itself
cause i thought it would be easier to navigate the chaotic folderpocalypse using the fileExplorer like u recommended a few minutes ago
but there is no actual hinge component anywhere
I expect you to use some common sense. The Standard Asset Pack is an Asset (The name is a bit of a clue) so it goes in the Assets folder
oh true
so how do you rotate the door?
I meant how do you tell the door to open
no, the answer I wanted was with a script. Which method do you use?
wdym
ty
btw is this an error?
the Method name
no
ill just send the script because im not sure what you mean
Yellow triangle warniing. Red circle Error
how are you writing code if you do not know what a method is?
idk
this vsc file booted up btw. It's all in C# too and I kinda I don't speak C# very fluently 
oh do you mean like void blah() {}
well that is a method, yes and the name would be blah
Ill just ignore it š
float GetRotation()
so you have no code that handles collisions?
and i set the target position in Update()
no not apart from hit.collider etc from the raycast
that does not 'handle' collisions
ive only been doing unity for a week i dont know this stuff unfortunately
so no i guess not
Then time to read
https://docs.unity3d.com/Manual/CollidersOverview.html
and maybe do !learn before you go much further
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
{
var values = Enum.GetValues(typeof(T));
int random = UnityEngine.Random.Range(0, values.Length);
return (T)values.GetValue(random);
}```
How do I actually use this function to get a random enum? It doesn't let me pass in the enum
RandomEnumValue<YourEnumHere>();
trying it now thanks
thanks it works ``` LootType randomLootType = SpawnAlgorithms.RandomEnumValue<LootType>();
you should be able to do
return (T)UnityEngine.Random.Range(0, values.Length);
why are all the material assets purple?
Please do not ping me into all your questions, that is not the way this server works
Also google before asking, there are a million explanations for this on the web
Materials incompatible with currently applied render pipeline
Hello, I have a question about public variables. If I have a script called Movement and I have multiple Movement scripts in a scene. Inside the script I have a public variable for example speed. Now if I change speed from 10 to 5 would this be changed on all Movement scripts or only the one Movement script I specify?
On only the one you specify if not static
if you change it in the script it wont change ANY existing instances
so if I make it a static variable it will change in all the scripts?
change it through the inspector if you want to change it for only one
I want to change all of them at once but I dont want to have to get each of the scripts
then static is what you want
Static fields can't be serialized, so they won't appear in the inspector, mind you
static is what you want only if you want to change them during runtime
Aight that is great thanks guys :D
Anybody know how i can Fix that ? In find nothiong at google:D
This happens a lot, the force applied horizontally + the friction of the surface is making the object be stuck in place instead of falling; just make the places where that can happen have 0 friction
i find that hard to believe
but ya, most solutions are to use a physics material thats using low friction. and apply it
Thanks
I got this off a google search but im getting an error in the enum.GetValues portion. Do I have to pass in the enum?
have you bothered reading the error?
yes it says Enum doesnt exist in the current context
What are you trying to do exactly?
I notice a lot of errors here
So first why writing UnityEngine.Random?
but I dont know how I would be able to pass in an enum without defining it
thats right, you're probbaly missing the namespace
I want to be able to have it use any enum
do you know what that is ?
Use just Random
then dont copy code you don't understand ?
I have to use UnityEngine.Random because im using System;
i wonder how super mario 64 camera works
Why not adding directly using UnityEngine?
Because System also provides a Random class.
You can use another using directive to fix the ambiguity, though
im using both
using UnityEngine;
using System;
using Random = UnityEngine.Random;
Oh, understood
what does what mean? You were missing the namespace then
Did Unity not override default Random?
that implies you don't have using System; anywhere
ah i see now
it doesn't "override" anything
UnityEngine.Random is a class and System.Random is a class
Unity has nothing to do with your code
If you have using directives for both UnityEngine and System, Random is now ambiguous
I changed the class to where that function was and the erorr came up the new class doesnt use System
thanks ill use that
So why using both Random? One is better then the other?
they aren't trying to use both Random classes
they're not
they just happen to want something from System and something from UnityEngine
and this winds up making Random ambiguous
Got it
the compiler wants to know which Random you want since they exist in both Namespaces
I misunderstood what he was trying to say
is there an equivalent of findobjectwithtag for spriterenderers
basically i want to change sprite sprite using the spriterenderer attached to the gameobject with the "heldweapon" tag
GetComponent
not tag
There is no equivelant.
You do the find and then getcomponent on the right object
Or just drag and drop
better if you can to just have a serialized field ^^
A SpriteRenderer is a kind of component. Components are attached to game objects. Game objects have tags.
I suppose you could find an object with a tag and then get a component from it
but that's getting really damn brittle
esp on the same object lul
u could write u some static methods that do that for u.. but it would end up searching for gameobjects itself
assign a reference to the sprite renderer in the inspector and you're done
wdym by brittle
it depends on a lot of little things
like there being exactly one object tagged "heldweapon"
and that the sprite renderer component is attached to that object, and isn't on a child of the object
why can't you just directly reference the sprite rendererer?
its fine since i will only ever have one player
bc this is for every weapon and theyre prefabs
so what?
lemme see this
i've made plenty of games with prefabbed weapons
If you can remove every find call in your code, things will be much better for you
Find is awful and should be avoided entirely
I've never searched for an object by name or tag, ever -- other than MainCamera, I guess (:
ok lemme explain right
im working on a roguelite type system
gonna have weapon pickups that are placed in by the level itself
I don't see how any explanation would justify Find() ?
we've been there, done that. thats why the suggestions
you especially don't want to be using Find if you've got weapons littered all over the level (:
If i subscribe to an event on OnEnable, It will listen to it whenever it happens no matter how long right? or until I unsub?
you want to have a nice Weapon component that gives you everything you need
yes
every time OnEnable runs, you will subscribe to the event
nothing is particularly "special" here
always unsub inside OnDisable or OnDestroyed ofc if you dont plan on reactivating it
in fact, it's good to realize that there's not much "special" going on in your code! I used to think calling Update or Start yourself was "bad" in some abstract way
All right thanks a lot.
but no! you can just do it whenever you want!
I'm making a Goblin Enemy. When it gets close enough to the Player it will start throwing Spears. The issues right now is that the bullet won't shoot left as the code doesn't tell it to do that. I just want to know how I can simply implement that. For context I havee three scripts, Spear Gob, Spear Gob Combat, and Spear. The Spear Gob script makes the move to Player and rotate if its going left. The Spear Gob Combat makes the Gob attack when close and spawn the Spear. The Spear Script simply adds a velocity at its spawn. 2D Game*
i already have a weaponinfo component that lets me define all weapon stats
Okay, so that sounds like a good place to store other references, too
main thing is how to do i get it to identify the spriterenderer of the player
What do you want to do to this sprite renderer?
void Start() {
rb = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(bulletSpeed, rb.velocity.y);
DestroySelf();
}``` This is the Spear Script
Action is a void return type delegate?
check the pivots, show code
Correct, with zero arguments.
swap out the gun sprite in the player's hands with that of the weapon the player wants to pick up
this gives no context.. You have to show also how you make bulletSpeed occur
Okay, so you aren't literally putting the weapon (from the floor) into the player's hands
hm I kind of got confused what does public static event Action OnSomething mean?
Drag that component into a field called PlayerRenderer
The weapon is just a thing that holds some stats and a sprite?
means the event is static
pretty much
Action is just a delagate with no return value / void @final kestrel
Okay, so just give the weapon class a Sprite field
Or you could give it a Sprite property, which would work like this:
[SerializeField] SpriteRenderer spriteDisplay;
public Sprite WeaponSprite => spriteDisplay.sprite;
How often do you for example use the Func delegates?
spriteDisplay is the sprite renderer on the weapon on the ground
Any way to destroy all the children of a game object? I keep getting errors about dependencies in the child objects I want to destroy.
{ internal void RecreateGrid()
{
foreach (var child in transform.GetComponentsInChildren<Transform>())
{
if (child == inventoryTilePrefab) { continue; }
DestroyImmediate(child);
}
for (int x = 0; x < xTileCount; x++)
{
for (int y = 0; y < yTileCount; y++)
{
Instantiate(inventoryTilePrefab, transform);
}
}
}
}
[CustomEditor(typeof(InventoryGrid))]
public class InvnetoryGridEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
InventoryGrid grid = (InventoryGrid)target;
if ( GUILayout.Button("Regenerate Grid"))
{
grid.RecreateGrid();
}
}
}```
WeaponSprite is a property that returns the spriteDisplay's sprite.
If I need events with return values for example
Not so often with events
ok so as you see i have a string which is the first text in the red box but if you look at the second red box i have 2 of the same things one being a string and i dont know what the other is but when i look through the coding i cant work out what im missing. this is the last thing i need to fix for tonight if anyone can point out what im doing wrong. https://hastebin.com/share/cuyewalive.csharp https://i.imgur.com/sbxU2v2.png
I read that it is not that used thats why I asked thanks
This is the Spawn Script when the Gob gets close to Player. ```cs
void Update() {
attackTimer = attackTimer + Time.deltaTime;
if (enemyFollow.canAttack && attackTimer > attackCooldown && !enemyFollow.canMove) {
Instantiate(spearPrefab, throwPosition.position, Quaternion.identity);
attackTimer = 0f;
enemyFollow.canMove = true;
}
}```
This is the movement Script but only the Flip code for Gob ```cs
void Flip() {
facingRight = !facingRight;
transform.Rotate(0f, 180f, 0);
}
}```
public static T MinBy<T,V>(this IEnumerable<T> enumeration, Func<T,V> metric, IComparer<V> compare)
Say you want to make an event but your method to subscribe needs to be a Task because its async. Func is perfect there
This method takes a function that takes a T and returns a V
I called it "metric" because it's the metric I'm using to compare values
So it calculates a value for each item, then compares those values, then returns the item with the lowest value
oh okay
I dont know async functions and tasks yet š¦
You use System.Action when you're performing..an action!
well I barely do either :p
i really need to figure that out sometime soon
now that we have that Awaitable doohickey
They're nothing complex. You switch out Task from void and add async keyword, now you have an Async method š
System.Func is used when you need a mathematical function: something that maps from a domain to a range (:
ok whats the best alternative for these
I think I know the solution. I just need to have the Spear know what rotation the Enemy is at its spawn initiation. How could I do that?
The enemy could tell the spear what its rotation should be
I posted a link above.
https://unity.huh.how/references
Either drag and drop, or if not possible, you pass the reference returned from Instantiate
pass it in the instantiation
Do this after creating the spear
a function that returns Task. async is used to perform tasks asynchronously yes but I never had to use it so I'll probably wont get what this means till I use haha
You can reference the spear prefab as a Spear (or whatever you named the component) instead of as a GameObject
That way, you can just do:
Pass what in the initiation?
Spear spear = Instantiate(spearPrefab);
spear.startRotation = transform.rotation;
I'll try
pretty much what Fen wrote above there, or do it Inline the Instantiate method
I have a somewhat simple question. How do you manage the scripts? Do you follow solid principles or just try to follow and yeet the rest?
too abstract!
Solid is gonna help you the most, if you can.
You cannot destroy transform like that
One of my main objectives is to get rid of nasty coupling
Like I have a script which has enemy health and other properties. Is it that bad that I put methods in it?
things that surprise me when I try to extend my code
you're trying to DestroyImmediate on the Transform component @hybrid gust
not possible
Why would methods be bad?
Since it goes against the single responsibility no?
That doesn't violate SOLID
Ah, I shoudl reference the gameobject itself and not the transform then?
I didn't even think of it like that
It does not
the single responsibility principle is cool until you have to make a game
imo
you either have props or methods in a class
what?
Ah okay
No.
yeah you wanna destroy gameobjects, do note that DestroyImmediate is for mainly for editor/assets
you prob just want Destroy
Uhh i read it somewhere
that sounds like...the single-kind-of-member-principle, which I just made up
Haha
Yeah this is code for a editor thing
You misread or the person was wrong
Could be yeah. Well
a core tenet of object-oriented programming is to create objects that hold both data and logic
I think its best to learn SOLID thru fucking up
yeah
SRP means everything should be part of a single responsibility.
In your health example, you would have things like variables CurrentHealth, MaxHealth etc and methods like ReduceHealth etc
Health class has the responsibility over health
make a game, find out what blows up in your face, and learn from that
Anyne able with one last issue for today please #š»ācode-beginner message
I learn everything through fucking up so thats a good idea
Once u have extremely spaghetti code youll appreciate what SOLID tries to do
I'm getting an error. What do you mean Spear? The Spear Script or the GameObject prefab?
yes these are all part of the HealthScript which itself is the Responsibility
Spear is a type.
Its kind of hard to understand SOLID unless you actually mess something up
I'm guessing you have a component that you attached to the spear
I decided to call it Spear
Ahh okay I get it
dont copy code mindlessly š
That is. I have a Spear Script.
Diamond whats the error?
I know, I tried to remake it with my code. But I cannot find a way
speaking of fucking up. I just deleted an object i didn't want to because GetComponentsInChildren also includes the parent of those game objects apparently
wdym Instantiate takes in a Rotation, just pass it through the parameter
I learned some stuff on a web development course. Abstractions interfaces why they help you write loosely coupled code and all but when I'm working on a game. I just aim for shit to work. This is probably normal right? š
It includes the object you called the method on.
@turbid bridge whats the error?
oh, right, you could just rotate the object itself
