#💻┃code-beginner
1 messages · Page 121 of 1
Fair
this kinda is a headache ngl cuz its a very specific case, like for the ui i need to use images, and for the game i need to use sprites.
hey
do you guys put all your class vars together ? or do you split between the ones that are shown in the inspector and the ones that arent ?
what does "using images even mean", You can put images perfeclty fine on ui..its not diff than sprite renderer..
anyway this is a coding channel. Further questions should go in #📲┃ui-ux
i split my scripts between responsibilities
when i can..
if you have one script, do you split or not ?
nothing is public, only properties and some methods
no , 1 script does one thing specific
yeah same, but im wondering if im not losing time by making two diff blocks for the inspector
i mean the vars
hii guys, i'm trying to make an enemyAI in which the enemy follows the player and attacks from range of 8 unit but it everytime rotates into different direction rather than facing player direction, i dont't know why its happening
forgot about the inspector, thats just the editor
whats more important is how clean code is (and functional duh)
can you show code also show your Pivots not in Global mode
and Center should not be selected, should be Pivot
pretty sure your Enemy is turning correctly
everything else as child is just parented to wrong forward
guaranteed xD
namespace GDL_Tutorial
{
public class EnemyShooter : MonoBehaviour
{
[Header("General")]
public Transform shootPoint;
public Transform gunPoint;
public LayerMask layermask;
[Header("Gun")]
public Vector3 spread = new Vector3(0.06f, 0.06f, 0.06f);
public TrailRenderer bulletTrail;
private EnemyReferences enemyReferences;
void Start()
{
}
void Update()
{
}
public void Shoot()
{
Vector3 direction = GetDirection();
if(Physics.Raycast(shootPoint.position,direction,out RaycastHit hit,float.MaxValue,layermask))
{
Debug.DrawLine(shootPoint.position, shootPoint.position + direction * 10, Color.red, 1f);
TrailRenderer trail=Instantiate(bulletTrail,gunPoint.position,Quaternion.identity);
StartCoroutine(SpawnTrail(trail, hit));
}
}
private Vector3 GetDirection()
{
Vector3 direction = transform.forward;
direction+=new Vector3(
Random.Range(-spread.x,spread.x),
Random.Range(-spread.y,spread.y),
Random.Range(-spread.z,spread.z));
direction.Normalize();
return direction;
}
private IEnumerator SpawnTrail(TrailRenderer trail,RaycastHit hit)
{
float time = 0;
Vector3 startPosition = trail.transform.position;
while(time<0f)
{
trail.transform.position=Vector3.Lerp(startPosition,hit.point,time);
time+=Time.deltaTime/trail.time;
yield return null;
}
trail.transform.position = hit.point;
Destroy(trail.gameObject, trail.time);
}
}
}
not please use Links
#854851968446365696 message
how do i fix that?
make sure gun is parented to forward of Enemy
the correct one
In Local Pivot mode
for gods sake use Debug.Log.
this direction.Normalize(); is nonsense
i was just trying to follow a tutorial , not my fault😫
yes, your fault for doing so blindly without engaging your brain
okay
thanks!!
It doesn’t let ke touch anything in unity and the loading doesn’t stop
Cam anyone help
How do i do multi threading to make performance better?
Or is multi threading just a thing that is there on all unity projects
The word "multithreading" should not be uttered in beginner code
job system
Eh i just know it from trying to make gmod performant on my potato pc
Job system is what you would do but if you're posting here chances are your performance issues are not related to threading
Try using the profiler and finding out where the problem actually is
I dont have any extra if checks, or.. ehm ehm.. random empty update()s. I also tried to minimize garbage collection, whatever that even means
But my code has a large delay on my cpu
Also i use unitys object pooling for bullets and impact effects in my game
So check the profiler and find out why
then write your own pool
Is the unity one bad?
you said it is slow
I meant i did that to increase performance
Until you profile the game and find out what is slow, you are just guessing. Get some data, and figure out what can be done to fix it from there
Who knows, you have no information as to what the problem is
first, can your code multithreaded? (moving rb can be multithreaded but modifying BVH/space partitioning not)
Lets sey there are no problems, can it make performance better by spreading the tasks between multiple cpu cores?
Whats a bvh?
If there's no problems then there's no performance to improve, you'll hit your target framerate and more performance won't actually change anything
bounding volume hierarchy
afaik modification of any tree cant be multithreaded (at least it has to lock the whold subtree)
!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.
Hi everyone... https://paste.ofcode.org/32P9EH6DAxdKwKvL9X8Fr4h In that code i have three big methods in the end of the code, and i wanna move them into separated scripts to keep the organizacion of my code... my doubt is if you recommend me to move them into separated classes or into a partial one of the one they are currently in
I listen you all
🙂
If the functions are only ever used in this class then there's no reason to move them anywhere
There's a bit of repeated code you could probably extract into a method, like this bit here
You do code that looks basically like this but with different code in several places, that could be a function with those text strings as parameters, and you can call that function instead of doing this in multiple places
Yeah, but this three last big classes are going to be much bigger... and i think is not quite good to have 200 code lines into one script... isn't it? I don't know too much about clean code hehe, so i'd like to know what you thing about it
Hmm, true
i'll take a look to that
You'd still have 200 lines of code, just in multiple files. Moving the problem elsewhere doesn't make it any cleaner. Instead find repeated sections of code and make them into reusable functions with parameters
nice tip, thanks!
so, this should find the component "Unit" for each gameobject that has its collider in this list
This code will loop over each object in explosionHits then set enemyHealth to the same Unit component in this script's object or its parent over and over again
oh I misunderstood the documentation then- if I want to change a specific integer in the component, how could I do that?
You'd actually change that value instead of just getting the component
and how could I do that?
With = usually
I meant like- how could i find that specific value in the Unit component of a different gameobject?
You would get that component from that game object, instead of this one
pretty sure replied this yesterday
#💻┃code-beginner message
then the code you used is completly wrong
I made this with a Untiy documentation I found
But I'm not sure how to make it properly
gpt code
Yes
!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.
Also
all you needed was rotate towards 🤷♂️
Can you explain me how it works? How would I define the "face" of the object?
just set your player as target and ur done
just make sure the gizmos are correct in Local Pivot mode.
And wouldn't I need to define a facing side for the object?
Okay
Thank you
ok np. try it out and let me know how it works out
okay thats just kinda funny
Okay I will
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
verticalMove = Input.GetAxisRaw("Vertical");
if (verticalMove == 1)
{
jump = true;
}
}
void FixedUpdate()
{
controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
jump = false;
}
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
if (Input.GetButtonDown("Jump"))
{
jump = true;
}
if (Input.GetButtonDown("Crouch"))
{
crouch = true;
}else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}
}
void FixedUpdate()
{
//move the Character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
Following a tutorial and I want to get the jumping and crouching working on just the left analogue stick (trying to learn so it's applicable to fighting games) instead of buttons. For some reason when I try to use the y axis for jumping it sends me to space vs when I use the button jump it's fine (I'm using the Character Controller 2D script from the video, there is no double jump so it's not repeating the jump call when in the air)
Also using the dpad would be nice but one step at a time
and I assume I can do that with GetComponentInParent
and the colliders are the colliders of other gameobjects
If you want to get a component in the parent of one of those colliders, call GetComponentInParent on one of those colliders
right need to figure out what that is
What what is?
calling
You should probably familiarize yourself with the basic terminology of C# before attempting to make anything in it
oh its just methods-
Have tried
Adding verticalMove = 0; underneath setting jump back to false (slightly better but still go to space without the fastest of taps on up)
adding jump = false; right after setting it to true in the if statement (no jump)
Using verticalMove >= 0 in the if statement (make problem worse)
Am also using a controller with a digital joystick so that the value should always be -1 / 0 / 1
Now I'm getting an error that says, "Cannot implicitly convert type int to UnityEngine.Color", here's the code: https://pastecode.io/s/rd1h57ms
What is a cinemachine camera? Im trying to learn how to transition between cameras and every tutorial says cinemachine
An integer is not a color
You are getting a random number between 0 and the length of your array. That's not a color
How do I fix it via code?
You should probably set the color to a color, not an integer
should use this https://docs.unity3d.com/ScriptReference/Random.ColorHSV.html
can you screenshot what that code looks like in your IDE?
Presumably they want a random color from a list rather than a simply randomly generated color
Ah okk
The random number you get is in range of your list, now access said list with that number to get an element
wow, i'm surprised it is actually configured with that horrible formatting
Yeah
try
{
triangles.Add(pyramidFormation[l][i].GetComponent<NodeBehavior>().index);
triangles.Add(pyramidFormation[l + 1][i].GetComponent<NodeBehavior>().index);
triangles.Add(pyramidFormation[l + 1][i+1].GetComponent<NodeBehavior>().index);
} catch (Exception e) {
Debug.Log(e);
}
So I have this fairly simple code here, lmk if i have to show more code here, but im logging an error that Object reference is not set to instance of an object. I'm not too sure what I did wrong, again, lmk if i need to show more code
And how do I do that?
Why so many get components, just make the list of type NodeBehavior
Wait till you see longer snippets. It's like that but on all the lines. No indentation, everything is packed up like that
pass the index you get from random to the array
oh i know, i've seen their war crimes
Do you know how to get an element from an array
I think so.
then do that
theres some other stuff I do with that list in other parts of the code, this isn't the only instance where i use the list
Do the other parts where you use the list involve you getting a specific component from it
yeah, transform
All components have a .transform property. Make your list of type NodeBehavior and use .transform when you need that
The debug log shows that I'm actually never setting it to 1 if I tap it quickly enough though it still jumps too high, if I hold it and it actually sets to one in the debug I'm in space
Okay then show that instead of code where you don't do that
alright, I will. Do you know why theres an error though?
What line has the error
No, I said show one where you are getting an element from an array
This is the same code
great you got the random Index, but where is the array element?
Okay, now show code of you getting an element from an array
the first triangles.Add()
what is example2 🤔
I don't know how to do it!
Then either triangles, pyramidFormation, pyramidFormation[1], or pyramidFormation[1][i] is null, or it doesn't have a NodeBehavior on it
#💻┃code-beginner message
Then you should say that when asked
It seems it does, but only for a few seconds
its correct
Your model however, is not
does anyone have idea if its possible/hard to make a way, that the player is being recorded from a perspective while playing, the whole time? and that that video gets saved somewhere and can be shown at a given time? sorry if im unclear, im new
How can I correct that?
In Unity the Blue is forward
put the Model on a child object and rotate to face the blue part
the code is working tho
very easy to do but the performance impact would likely be prohibitive
yes in Unity, Blue arrow is the Forward of any object
also Don't use Center mode for pivot, use Pivot
you don't want weird issues later
looks like pyramidFormation[l][i] is null
Done
Where do you set it
heres the code that sets it:
NodeBehavior currentNode = pyramidFormation[l][i];
currentNode = nodes[nextAvailableNode].GetComponent<NodeBehavior>();
currentNode is a reference to pyramidFormation[l][i]
So it'd seem that nodes[nextAvailableNode] does not have a NodeBehavior
This is one of the reasons you should be using that as your type for all these lists
It won't be possible to put something in the list that doesn't have a NodeBehavior
alright, I just made nodes a NodeBehavior list
also that code makes no sense. changing currentNode will not change pyramidFormation[l][i]
it wont?
Ah, right, that too
Okay so the child is looking towards the blue arrow of the father
no , it wont
No, you're changing which NodeBehavior the variable currentNode points to
Should I put all the logic in the father or ir in the same capy?
could itbe that the game will lagg? im not planning to make a game with amazing shaders or anything like that
all components except mesh go on parent, but you outta fix that pivot
Since it's still facing wrong
It will lag, making real time mp4 at run time is very, very heavy
ah
i keep getting this error when trying to run game what should i do?
how does, fortnite do it for example? like the match replay? it just needs a recording of the gameplay from another pov
start by configuring your !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
What is myRidgidbody
I dont know how fortnite did it, I didn't develop it. How I would do it is by using async threads with reduced fps if I even wanted to get close to it
It records the positions of everything at a fixed rate, and replays them. It's less expensive than recording to a file, but would still produce a consequent file size, especially if you have a lot of objects in your scene
Not sure how fortnite does it but if the game is determanistic you can just record the inputs and replay those as a script, that's how fighting game replays work
this should do that, right?
This is exactly the same as your original code
You're still calling GetComponentInParent on this object
you wrote it wrong in one you added a d in myRigidbody in the other one you didnt
Also there's nothing in your foreach loop you end it before you open the curly braces
and that is supposed to do what exactly?
it doesnt neccesairly need to be a file, i just need the gameplay to be shown at some point in the game, i could split it up, but want to reduce cuts at minimum
interesting.. i could just make the 'fake player' re-act what the actual player did?
no way you are going to be keeping an mp4 in memory without problems
what do you mean?
Encoded video is big
as long as the same inputs always create the same outputs it should work, idk I'm brand new but it seems like a simple concept - if there is any form of rng this won't work
I am trying to get a reference to another component ("Unit") on each gameobject whos collider is on a list
Then get the component from that object
call the function on that
do you have any idea the amount of space an mp4 will use?
yeah im new aswell and im trying to figure this out, jus brainstormin :)
Can anyone guide me for animation on a character
My character has more than one walking style
so how can i set it to one random style when it spawn
okay, yeah thats true, i guess ill need to make cuts, but itll still be big im guessing, could there be a workaround? or something else?
I do not know how to get said GameObjects
as I only have their collider components in a list
You have them
that's what you're looping over
Use that
The thing you record is stored in memory until you write it to a file for example. If you do nothing with it, it will accumulate, fill up your RAM, and your game will crash because it will be out of memory at some point
Ok, so your code does not do that at all
I am aware now
oh okay
thought that this only got the collider components into a list
if it gets the gameobjects that makes my life easier
It does
sooo, what if it writes whilst recording? lets say the output (the screen of the recording) will just be playing while recording, and then when stopped recording it will loop to certain cuts, so it doesnt record everything? idk im just brainstorming
Colliders are on game objects
Components all have access to all of the GetComponent methods
oh okay
that clears things up, thanks
got confused by the wording, as I thought I needed to get the gameobject that the collider is on, and then get components from that
Yes you'd want to write the images (or whatever) to a file frequently enough so it does not fill up your memory.
so if i do that, record and write at the same time, then play/loop when needed, this could work and the performance would still be okay?
Depends on the capture resolution and the computer, so can't say.
Try it, and if you get performance issues, use the Profiler to see where exactly it takes the most time
resolution will not be great, lets say itl be played on a tv from the 90s ;p, still will be visibile and clear enough tho. still, thank you and the rest for helping :)
nevermind
whats this otherComponent supposed to be?
both of these are wrong
look at the warning on your foreach line
man, C# basics
this?
no, the one that is clearly underlined
oh i see the problem
You need to put that inside your foreach loop
Right now your foreach loop is empty
is there a place to explore what custom codes can add to the inspector ?
like variables and stuff
seen a vid which added those
made me think what else is there to add
Basically anything.
https://docs.unity3d.com/Manual/editor-CustomEditors.html
ty
Hi, i have a little problem, i am making my first 2d plataform. I created a dead zone for when you fall, the deadzone works but it works only if you touch it for the side, if you fall in it you dont die and idk how to fix it. Here is the code of the DeadZone:
how could i put a delay between lower and raise to prevent both happening at one click
you have to use the same button?
yeah
i cant help u im very new here
Ok
Try making the collider of the death zone thicker.
If you don't move the player in a way that uses the physics system (like using a Rigidbody), it's possible that the player will pass through without being detected.
Modifying the transform.position directly does not use physics for example
he just stand there
Then there's a collision, it's just not tagged properly
So it doesn't pass the if statement, and Die() is not executed
that´s the problem because is tagged correctly
and if you touch it form the side works
an the box is very thick
Make sure by logging what you hit
Debug.Log($"Hit object {collision.gameObject.name} tagged {collision.gameObject.tag}")
Then check the console when the player hits the object, and make sure it's correct
okey
Idk where to put it 😅
Whenever you collide, so in your OnCollisionEnter2D
hey, i'm trying to create a replica of flappy bird, but for some reason the bird object auto rotates while playing. Anyone knows what I can do to fix that? It's the Z rotation that does that
ok it collides so now i am very confused
It always collided, because your player was standing in the air
It's the if statement that didn't pass, making it seem like it wasn't doing anything
Just make sure that in the console it says that it collided with an object that has the correct tag
I fixed my problem for now
It logs twice, is the script on another object by accident?
From what I see it's meant to be attached to the player only
im going to check
anyone know how to prevent this?
yeah it was in another object by accident but we are in the same point 
Put another log, but this time inside the Die() method. So you can see if it gets executed
Hey, so I have a script where I reference the Weapon : scriptableobject class. I thought this meant that any class inheriting from Weapon should be able to be put into the inspector for a Weapon variable is this wrong?
If i have a gameobject saved into a variable what would be the best way to access the child of that gameobject
asked the GPT and it said this
You indeed access parent and children from the .transform
There are plenty of ways, and they depend on your use case
If you just want a specific child, why not drag the child directly into the slot, for example
Like on a variable exposed in the Inspector
what can be the Log
Are you getting any errors in the console? Make sure you didn't disable them accidentally (3 buttons top right of the Console tab)
i dont have any error its like the character cant make the transition from fall to death
i tried to make a transition directly fall to death
but it doesnt work either
i am going to re edit the animator i think
how should i learn c# there are so many different people telling me different ways to start and its really overwhelming
yt tutorials 😀 👍
idk
im new here too
i made a beginner unity course
but now im using yt tutorials
Yep now that you have the confirmation that the code is executing, it's an Animator issue
thank you so much and sorry for the troubles
I'm not very good but I learned c# using brackey's tutorial on YT. You can follow it but be sure to also write the code, not just watch it
okay
Right so- I assume this won't work, will it
( second image is in the script of the unit component
are you sure you are getting the right kind of Unit component inside that foreach loop? hover over it to see the fully qualified name
~~Camera isn't recognized as a Class in my VS
its not colored like a class and isnt giving me any methods
i tried regenerating VS files but nothing changed~~
just says this
then there is likely some context you are not showing
well i restarted VS and everything got fixed, weird
this is the only relevant code I can think of- any tips on what the important context might be?
well for one, it would be great if you stopped sharing screenshots of code
No
Be mindful, if someone requests your code as text, don't send a screenshot!
in this coding convention:
Public var: exampleVariable
Private var: _exampleVariable
When serializing a private variable using [SerializeField], should it remain with the underscore in front of it or I should remove it?
the convention is about the accessibility, not whether it is serialized or not
alright
you should also share what the actual error says as well as the full code for both of the classes
any idea?
i set the project id/envoirment/ my id/pass etccc
there it is. you've defined your enemyUnit variable as a Component variable and not a Unit type
oh okay, thanks
We could also have seen that if you shared the error
how to add a permanent contextmenu to all my behaviours? 
[MenuItem("CONTEXT/MonoBehaviour
```hacky 
Something like
[MenuItem("CONTEXT/ComponentName/My Header!")]
private static void ContextMenuAddFunction(MenuCommand command)
{
var component = (ComponentName)command.context;
// rest of your implementation
}
https://hastebin.com/share/qoyuwenilu.csharp hey peeps, im trying to make a conga line of gameobjects to follow a player object, using a public static array for the transforms but the array never seems to work, it never adds in the playerscript.transform as the first item. is a public static array even the right approach for this
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
theres very little info for me to work off online for this, so i wonder if i need to articulate it differently
Does the followers[0] = playerScript.transform; line in Start() lead to an exception?
Because it seems you haven't even initialized the array yet when you call that
yup!
you never initialize the array
Also maybe an array isn't the best choice for something like this that can get dynamically changed.. I'd use a List<>
honestly a static list isn't necessary either. when one of the objects that needs to follow another is spawned, just pass it a reference to whichever object it needs to follow. and have whatever is spawning them keep a list of what has been spawned
yeah i could do that but if one of the objects gets destroyed in the middle of the chain, i guess it would have to pass the subsequent object into its place? which is getting ahead of myself ability wise
have whatever is spawning them also manage destroying them. then when it goes to destroy one, it also tells whichever is following it to follow whatever the destroyed one was following
ok sweet, will do that
Dontdestroyonload game objects wouldn't trigger their start function on a scene change, is that correct?
correct, Start only happens a single time in an object's lifetime
okay so I'd need some like scene manager to trigger any kind of things on a change cool, thank you thank you!
there are events you can subscribe to like the sceneLoaded event
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html
How do I send code here again?
!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.
so I got the door to kind of work how I expected using a hinge. However, once it reaches its limit you can keep pushing it and it gets all like, jittery and weird
I want it to basically become rock solid, as solid as level geometry, if you are trying to push it past its limit
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hanger : MonoBehaviour
{
public bool hanged;
private Transform hangerTransform;
private Animator ani;
void Start()
{
ani = GetComponent<Animator>(); // Ensure correct component retrieval
}
void Update()
{
if (hanged) // Use comparison for boolean value
{
transform.position = new Vector2(hangerTransform.position.x, hangerTransform.position.y); // Assign 2D position
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("hanger")) // Match tag exactly
{
if (Input.GetKeyDown(KeyCode.Space))
{
hangerTransform = collision.gameObject.transform;
hanged = true;
ani.SetInteger("hanged", 1); // Use correct method for setting integer parameter
// Obtain transform directly
}
}
}
}
i dont know why the collision wont work
guys how much would it cost to make a game with these features:
Match-Three Puzzle Game:
Blocks:
Shapes: Squares, Circles, Diamonds, Triangles, Hexagons.
Colors: Red, Blue, Green, Yellow, Purple, Cyan.
Special Blocks: Star (wildcard block that matches with any color).
Power-Ups:
Line Bomb: Clears an entire row or column.
Color Bomb: Clears all blocks of the same color it is swapped with.
Lightning Block: Clears all blocks in its row and column.
Super Swap: Allows one move that can swap non-adjacent blocks.
Scenes:
Coral Reef: Bright, underwater-themed tiles with a moving water background.
Enchanted Forest: Green and earthy tiles with animated background featuring subtle creature movements.
Space Nebula: Dark tiles with a starry background, featuring occasional comet animations.
Game Mechanics:
Combos: Matching more than three blocks gives increasing multipliers.
Obstacles: Unmovable blocks or chains that require multiple matches to remove.
Vertical Stage Strategy Game:
Characters:
Basic shapes representing different sea creatures, each with a numeric value.
Colors: Differently colored to represent various power levels (lighter colors for lower levels, darker for higher levels).
Gameplay:
Progression: Each 'eat' increases your character's value.
Strategy: The player can only move up to the next stage by clearing the current one.
Power-Ups:
Shield: Temporarily allows your character to eat an opponent one level higher without getting eaten.
Double Points: The next character eaten doubles in value.
Freeze: The points needed for the next opponent increase are halved.
Environment:
Simple backgrounds that change color or have minimal animation to indicate level changes.
If you have to ask, probably too hard
How come
If you don't know enough unity to gauge the scope of a game then any complete game is probably too much
two things, first make sure that OnCollisionEnter2D is being called
second, do not use Input.GetKeyDown inside of OnCollisionEnter. GetKeyDown is only true for the first frame that you press the key which may not even be a physics update frame. OnCollisionEnter2D is also only called on physics updates and also only the first frame the collision happens. So you have to have inhuman timing to match those up. consider checking input using GetKey inside of OnCollisionStay or just flip a bool in OnCollisionEnter/Exit and check input in Update when that bool is true
i would do it for ten bucks if I didnt have a project of my own
The Three Commandments of OnCollisionEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt have a 2D Rigidbody on at least one of them
😭
so I what would I add instead?
I would try to find the most similar game you can to your own game and research its production costs
People who use the cry emoji often dont want to put any work in themselves, just saying
did you not read what i said? i gave you two options for what to do instead . . .
how are the player going to get inside the collider if I have istrigger on?
I think what is happening with my door is that I have a kinematic body pushing on the hinge joint, and I'm thinking for whatever reason the hinge joint doesn't take priority and wont tell the character controller to stop?
If either of them are triggers that would be the problem
If either of them are triggers that would be the problem
Either make it not a trigger or use the trigger function instead of the collision one
how to edit heirarchy search bar via code 
is it a technical limitation that you can't make joints have solid limits against a kinematic body
Yeah pretty much. Joints are never 100% reliable, even FixedJoints can go over the limits
And a kinematic body basically has infinite mass when it comes to collisions
why is it in red but it still works?
so what is the solution? is it just impossible for a kinematic body to interact with a non kinematic body?
I basically have a player with a character controller and a kinematic rigidbody
I want this to be able to push a door open, but not jitter when it hits the limit
and just block the player
I tried making it not kinematic but unity says I cant
Huh? Does it have a mesh collider or something?
But what does unity say exactly, why cant you make it non kinematic
you probably need to regenerate project files
Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported since Unity 5. If you want to use a non-convex mesh either make the Rigidbody kinematic or remove the Rigidbody component.
how do i do that
The door could check its own rotation and detect when it goes out of limits. When it does, manually rotate it back to the max allowed angle, then detect any overlapping RB's with an OverlapBox and move them away from the door
So it does have a mesh collider like I asked
Check child objects if it's not on the parent
Preferences > External Tools in unity
i updated the visual studio code editor
and it works
in package manager
wait no it doesnt
its just one asset tho
everything else works
yes and you recently added this asset so vs code does not recognize it. so regenerate the project files for vs code
oh for some reason my weapon gui planes had a collider
still doesnt work
lol when I make the RB Non kinematic it makes the player fly around like crazy
then close vs code and unity, delete the Library folder from within your project, then open them both up again
A kinematic rb will need different movement code, of course
I don't want to make the players movement based on physics because of case in point, how finnicky and glitchy physics sims in games always are
maybe I should just make the door not really use the physics engine
@real falcon you could try this idea and see if it makes any sense
That is easier yes
Way easier
thats gonna take a long time to figure out for me how to code that, and I am almost certain it's going to look jittery when you teleport the RB back
how do I tell when the player touches it tho, and from what angle? and how does it stop when it touches the player, if the players controller stops it before it even penetrates?
Not if you do it right, but yeah it takes some time/knowledge tp imolement
still red
I remember now that the reason I went to a non kinematic door was because the door would push the player, which would cause depenetration that was jittery
OnCollision checks should work
even if it doesnt end up moving the player?
I dont remember all the limitations of kinematic
should this new door even have a rigidbody?
disable the collider on the door when its opening/closing
well, I don't want it to go through the player either
Thats how a lot of games do it yes
the door I'm looking at as an example is from Portal 1, I remember there being a door that you can open and it swings open, but if you try to close it on yourself it just stops as soon as it touches you
and it doens't cause any jittering or anything like that
OnCollisionEnter only works if one of the ojects has a non kinematic rigidbody
which means my door will have to be non kinematic, which means it can bug out
any idea how to fix it?
Kinematic contact pairs are a thing too. Never used it myself tho
I want something that blocks the player without depenetration or jittering, but is also blocked by the player in the same way
if that didn't work then consider switching to a real ide that won't just randomly break
this is what im trying to access
i tried using visual studio
not code
same thing
it acts as pure terrain towards the player, and can only move if it's not touching the player whatsoever
It definitely did help, im figuring it out, and the animator overrider controller would go on tbe player? And i wouldvhave one for eavh gun? Eg dif reload animations.? But thats confusing, dude im sorry but do you think you could hop on call and i could screenshare and shownyoi what i got so we could figure something out, you seem way more knowledgeable abiut this than i am, snd i’ve been stuck on it for like a year, I’m willing to pay even, lmk!
works now
the OnCollisionEnter event doesnt seem to be triggering even if the door is non kinematic
its just not running
even when Im physically pushing the door, doesnt show that method runs
this is the players rigidbody
and the doors
ah I had collider instead of collision thanks
now the question of how to make a door with a rigidbody that the player cannot move at all
without settnig it to kinematic
nvm just set it to kinematic and enabled kinematic collision detection. It actually works pretty well now, I got it moving but stopping if it touches the player and it does not appear to move the player at all, nor does the player seem to be able to move it at all
I get intense lag if I push into it at certain angles but I think that's my own code. I'm worried about coding it rotating in response to collisions but maybe it will be easier than I expect
How do I change variables across scenes in unity?
Either turn off gizmos generally, or disable the specific one
https://unity.huh.how/interface/gizmos/disabling-icons
why have you sent a screenshot of a component? That's not where you disable gizmos
Where then?
I'd also note that this is not a code question and you should have asked in #💻┃unity-talk
Correction: How do I change variables across scripts?
Serialize a reference to the other script and then just access it via the variable of whatever instance you want to change https://unity.huh.how/references/serialized-references
can somebody hop into a call with me and help me figure out something?
Can’t hop in a call but what’s the rundown on your problem
im trying to make a gun
Blender
and im trying to also make it emit spark particles when it shoots
i have a model and simple shooting (raycasting not projectiles) and reloading
Ok so you need an onclick function, have you worked with inputs yet?
Ok I think if u press edit, Inputs, and then find mouse down inputs
For the code u will need the name of the type of input you’re getting, for example moving your player vertically takes an input of W, S, or Up arrow, Down arrow. This input is called “Vertical”
Should be toward the top left of the editor by file
(I’m also pretty new but this is something I know) xD
i dont see inputs but thanks for the help anyways
Ok it’s actually in ur project settings tab but here’s the type of code you’ll want:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// Spacebar was pressed
}
if (Input.GetMouseButtonDown(0))
{
// Left mouse was pressed
}
}
The update function is in every script by default, it runs every frame. “GetMouseButtonDown(0)” being a left click on mouse
In the if statement is where you would put functionality of your gun
For the reload u would use the “GetKeyDown(KeyCode.R)”
It would go on the object with your Animator component, so say you had a "pistol reload" and a "rifle reload", you could name the state for both to just "reload", and maybe you start with a pistol, so your default "reload" state in your animator controller could be your "pistol reload", when you swap to your rifle, you can then set the entire animator controller to your "rifle override animator controller", which will replace your "reload" from "pistol reload" to "rifle reload" - so in a way, youd need an animation for every gun that is different (for example if you have 4 different types of rifles, some may reload differently than others, while all the different pistols in your game probably reload the same way and can reuse the same animation) - I wont really be able to do a call or anything until after celebrations here, though if you have other questions, I can try to help, otherwise if your willing to wait about a week, I guess we could discuss it in DM
how to instantiate empty gameObject from code without any reference?
i only need it's Transform while it is on the scene
Instantiate()
Or even new GameObject()
Actually, no blank instantiate. I thought there was
it will not cause memory leaks, right?
only instantiating components outside of gameObject cause leaks?
What?
Do you know what a memory leak is?
in case of unity not really
It means the same thing in Unity that it does outside
Do new GameObject()
It will not create a memory leak unless you do something VERY weird.
You also can't instantiate components outside a GameObject
thanks!
so i have a door that opens if you touch it, the problem is it also opens if you touch it from the wrong side. I'm wondering if there's an easy way to detect if a given movement would end up intersecting an object
specifically, this method is what I use to rotate it. is there a way I can like, "preview" it and see if it would collide with anything before I actually move it?
if it's raycast based you could use one sided mesh collider.
You can also use three colliders setup, two flat trigger-only colliders for each side and one box collider that works with physics but doesn't trigger
How do I make it so that a collider only detects a single object.
Make a layer and set the collision matrix to only detect that specific layer
Or just let it detect more things and validate the collision before doing anything with TryGetComponent or CompareTag
Or a combination
hmm multiple colliders, good idea. how do I tell which one it touched tho?
I guess probably it tells you in a parameter
ah
except one with door box collider
thats a lot smarter than how I was thinking, thinking i'd have to calculate the direction of the door's motion as a vector and compare it to the direction of the thing you hit etc.
my solution can cause bugs if you move the touching body at high speeds
it can touch both sides if speed is too high
hmmm, at high speeds you can go right through the door without colliding with it
hey, does anyone know how to get the length of an animation for a runtimeAnimatorController/animatorOV's animation?
What are you going to do with that number? There's probably a better way
i knew someone was going to ask this
i'm using it for a coroutine
A coroutine that does what? Have you considered animation events or StateMachineBehaviour for your use case?
i've considered using the exit animation events however to my knowledge im unable to call instance specific functions for example
it'd make it a lot easier if i could use exit animation events though
~ also to answer your question it fires off an event to a non mono behavior class listener which changes frequently when the coroutine is done playing the aforementioned animations
can someone help me make prodecural generation for my 2D sandbox?
hope the information provided is satisfactory, obviously its a bit convoluted and a not a usual system however, if you're able to provide a better alternative im all ears
Wdym by "instance specific functions"? That's the only thing animation events can do if I understand what you mean.
it's essentially just telling the non mono behavior class instance that it's done the animation
if im able to subscribe and unsubscribe listeners to the endanimationevents via the class though that'd be more than sufficent
Not sure what you mean by endanimationevents
I'm talking about https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
You would need a MonoBehaviour as the listener here. The MB can call a function on your non MB
preferably this would be done outside the editor
i was refering to OnStateExit when i said "endanimationevents"
yes, ive just realized that now lmao, unfortunately i still had some issues with that somewhat
What issues
and my terminology wasn't correct
as i said i need to do something to specific class instances
StateMachineBehaviour lets you do that
OnStateExit gives you a reference to the specific Animator instance
From there you can do whatever you want. E.g. GetComponent to grab other scripts on that object etc
issue being im getting the compile time error CS0201
Sounds like you made some kind of basic C# syntax error
But I don't memorize error codes
thanks for the help in any case friend
ill look into what i did further
if thats the case
If you need help with the compile error feel free to share the code and the actual error message
solved my issue thank you friend, basic syntax error was all and i was able to fully solve my initial issue
i try to think of myself as well versed in Unity and ofc C# however, i guess we all make basic mistakes!
how do i make a simple item system, including consumables and items with abilities on activate?
Make each type of item an object. 
They themselves should be SO.
Then the item slot themselves into structs that holds that item object.
The item slot struct can contain things like count or something but most importantly the item representation scriptable object.
can we serialize a monobehaviour field and make them assignable in inspector, and be used in code for tasks like Destroy(monobfield)
like assigning a specific mb field, and not the object
inventory system is a wide feature, there's a tens of ways to implement them. Better check on google first and gather inspirations
You have three types.
List. Slotted. And multi slot occupying system something. 
One is just a list of items. You can sort them or filter.
Second is just a 2d collection of slots.
Third is something like Diablo where items can occupy two slots at once in specific shape.
ok
thanks
can anyone help me out on how to offset an XR controller?
depending on what you want to achieve straight up instances of a item class or instances of a class that inherits from a parent item class could offer more flexibility
although for beginners SOs would be better
so if i wanted to damage a player wiht a gun i know i need to send it thru the server first then the client, would i need to make a server script aswell as a script that sits on the player?
Entirely depends on the networking framework you are using
Sadly Im not familiar with mirror or steamworks but there is #archived-networking Im sure someone there knows a thing or two
thank you ❤️
Tank.
Hi, I chose the type of Scripting Backend: "LI2CPP" and I have a problem. I tried to look up a solution to this problem on the Internet, but either there were answers to the old versions of Unity and/or I did not understand how to solve it.
Problem:
but i don't want to use animator or animation
playerRb.velocity = new Vector3.zero;
playerRb.velocity = new Vector3(0,0,0);
can anyone explain to me why I can do the second option but the first one doesn't work? afaik they are the same thing (being used in update method in an if statement if that helps)
the console error doesn't seem to like that I don't have an argument with the .zero, but I'm unsure where I would but the () in the first example.
Vector3.zero is not a constructor, you don't use new with it
so i want to add fade effect fade in and out but using 1 button and not like fade in and fade out button like in the tutorials
but i don't want to use animator or animation
and i want it like this video
the game in the video is not mine
so im trying to make a lobbies list i have all the code but the scroll view isnt showing up neither is the lobbies?
and they are active
You aren't showing what is going on in the "Content" folder of the scroll menu at runtime so this is kind of hard to answer
As for the scrollbar disabling, it is actually functionality implemented by Unity where if the scroll bar would serve no purpose (eg. content folder is not big enough so scrolling does nothing anyways) it will disable set the alpha of it to 0 until it is big enough again
oh ok
@wild cargo do you know how to do this?
#854851968446365696 , don't ping users to help that haven't participated in the conversation yet
Also why does that map especially look eerily similar to Granny's map? Asset ripped game?
I've reread #📖┃code-of-conduct and I'm unsure if I'm allowed to help you or not, sorry
(might be wrong here though, as I said I'm not sure)
hey guys. i want to generate fuction that return random number using a gaussian curve with the magnitue from -1 and 1
the curve take 3 value (a,b,c) where a is the peak value of the curve , b is the lowest value on both end of the curve. c for the ammount of different where c = 0 mean its a straight line with the height of a, the more c increase the curve on both side get steeper
the problem is im bad at math ;w;
i want to do this for better number generation , generate from -1 to 1 and take the value on the curve
a must be 1/2
integral from -1 to 1 a dx=2a=1=>a=0.5
that means ont of the parameter in your function is fixed
integral of random variable over its domain must be one
You can use an AnimationCurve, set it in the Inspector, and .Evaluate() it when needed
ah thank gah
I think there is already a function (somewhere) that will return a normally-weighted random variable
imma try the AnimationCurve thing
Hello, I've been trying to fix this error for days but I just don't understand why it doesn't do it the way I want it even though I actually think everything is correct
Maybe one of you has an idea and could help me...
It would be really great
Kind regards
Ginsmex
This is the video I used for this
https://www.youtube.com/watch?v=ScxN04YeDj8&list=PLZ1b66Z1KFKit4cSry_LWBisrSbVkEF4t
In this tutorial for a 3D Endless Runner we write some code to display out coins collected on screen.
✦ Subscribe: http://bit.ly/JimmyVegasUnityTutorials
✦ Patreon: http://patreon.com/jimmyvegas/
✦ FREE Assets: http://jvunity.com/
✦ Facebook: https://www.facebook.com/jimmyvegas3d/
✦ Twitter: https://twitter.com/jimmyvegas17/
-------------------...
The error points to line 13, so either you did not drag-drop an object into the Coin Count Display inspector field, or you did, but it didn't have a Text on it
https://stackoverflow.com/questions/2325472/generate-random-numbers-following-a-normal-distribution-in-c-c
googled how to generate random number based on normal distribution....
I have it as text and I also specified it at levelcontrol using the C# script but unfortunately I can't get it to work
sry, I'm still a beginner
Okay it's not a Text, it's a TextMeshPro Text you have attached to that object.
The type is different, you need to use TMP_Text in your code
The tutorial might be a bit dated and was made before TextMeshPro was the mainstream solution
Okay, thanks, maybe you know tutorials where I can learn in the new generation
It's pretty much the only thing that changed sensibly, but you can filter your searches so they only include results from the last two years or so
OK, thanks for the great help
is calling a UnityEvent in the Update a bad practice?
UnityEvents are around 10x slower than regular events, so yes it can be if you're not careful enough
Use regular c# events whenever possible. Basic syntax is
public Action event MyEvent
You can opt out of using the event keyword btw.
What the event keyword does is prevent other classes from being able to call it.
And you also can't set it. Just add or remove methods to it.
Removing the event keywords allows anything to access, set, get, and call it. As long as it's accessible (public and stuff).
But then when the event keyword gets removed, you can only assign one thing to it (the action)
Delegates should be used in that instance
Could be wrong though, been a while since used delegates in my architecture
I think you can still assign multiple methods in a delegate. I'm not sure tho. :p
public delegate void MyDelegate();
public static MyDelegate MyDelegateInstance;
public void Test()
{
MyDelegateInstance += () => Debug.Log("test1");
MyDelegateInstance += () => Debug.Log("test2");
MyDelegateInstance.Invoke();
}
Yeah this works, and also delegates can be invoked from outside the class they're declared in
If it's not an event, you can use the readonly keyword.
Or make a getter setter and make the setter private.
public static Action MyAction;
public void Test()
{
MyAction += () => Debug.Log("test1");
MyAction += () => Debug.Log("test2");
MyAction.Invoke();
}
But for some reason, this also leads to the same behaviour.. what?
No need for delegates or events
So then when should you use delegates? Never?
You normally make your own delegates for explitness or something. Or use the ref, in, or out keywords.
If you have to write more boilerplate to them then there's no point
MyDelegateForSpecificThing says more than Action<Here's your input, here's your other input>.
public delegate void MyItemDelegate(int myInt, string myString, ScriptableItemData itemSO);
public static MyItemDelegate MyDelegateInstance;
// vs
public static Action<int, string, ScriptableItemData> MyAction;
Like this maybe?
Then the delegates can be reused easier.. but that's like the only benefit
And also the param names
This isn't a benefit actually.
They only need to match signature. :P
It is a benefit if you have a lot of them, or the same types
Like I said, you can also use it if you want to use ref, out, or in keywords.
Oh yeah because those cannot be used in Action<T1, T2 ...>
But I personally used custom delegates instead of Action. I keep refactoring and I want those warnings.
So events are basically useful when you want to create a delegate instance that can only be subscribed to by other classes, not called by
width, height, length is clearer than arg1, arg2, arg3 so yes custom delegate types are better for these use cases
Also depends on the name of the delegate instance you have.
For example, Action<int, int, int> OnGridCreated might already be descriptive enough
Again, it's not a benefit.
You don't see that in the tooltips, only in the declaration. :P
I'm pretty sure you only see. MyDelegate.
I guess unless you do a lambda?
You see it in the handler method, as when you make VS auto-create the method, it takes the delegate type's param names for the method name
It's useful for when the handler is not in the same type as the one declaring the event
And of course as a tool tip when you invoke the event
Ah.
hello!
im getting this error and my charachter is floating
UnassignedReferenceException: The variable orientation of PlayerMovementTutorial has not been assigned.
You probably need to assign the orientation variable of the PlayerMovementTutorial script in the inspector.
You can
what UnassignedReferenceException means and if you can't find any results come here again
its telling you how to fix it
assign orientation
That error is one of the clearest you'll be getting in Unity
ok thanks
im newwbie xD
do you know how to assign something ? its the field in the inspector.
or in code we use =
https://www.youtube.com/watch?v=HVucS70Z6Q4
This can also help, it's 2 minutes long
(could be 30 seconds but whatever)
Fix Unassigned Reference Exception Unity
and assing it to what
To whatever the tutorial you're following tells you
You might be doing this later in the tutorial, so it's possible to get the error if you test your game too early
simple saving and loading system ?
now the carema is floating
Then I suggest you !learn instead of copy-pasting blindly
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i have a project for university
huh
That's not a very good way of thinking
If you're not willing to put in any effort, why should we?
Do some of the beginner courses on Unity Learn, then come back
that's not a very good way of thinking
jki
jk
How simple do you want it to be? How much are you willing to learn?
If you want to make a very easy-to-set-up system, learn about PlayerPrefs. It has very easy to understand syntax.
If you want to make a more scalable solution with more types supported, learn about JSONs and serialization. This takes more time but is very much recommended
as of what i heared playerprefs are limited to variables, like does it support dicitionaries ?
Nope, neither does Unity's JSONUtility so if you go with JSON create your own SerializableDictionary or use something like Newtonsoft.Json
But JSONUtility is so dogshit I don't recommend using it for a project where you anticipate a lot of saving/loading
that doesnt feel like english
Wait one month and all of that will (hopefully) make sense
i just need a way to keep my player data when closing/launching the game
What does your player data consist of? An inventory, player name, EXP level, stats?
yea kinda
the inventory is more of a dicitonary with an int itemid , and a bool to know if its owned or not
For that kind of data you could use PlayerPrefs but I highly discourage it, because saving collections with it is troublesome
so thats what basically stressing me out
isnt JSON for programs hosted on servers? At least that's all I've ever seen people talk about/use it for. As in, you wouldn't really use it if your game didn't interact with a server somewhere
JSON is just a formatted text file
JSON is used very often in client-server communication (like it's the only method), but that's also what I thought until I learned they are also used very often in local files too
yeah this makes sense. like I said I've only ever seen it being used to interface with servers, at any rate I'm up to my ears learning C# rn so I stay away from additional concepts for now because it will probably only confuse me further
I still recommend you learn about JSONs, should take no more than 4 hours to get some kind of system working
That 4 hours is just an approximation, that's how long it took me to learn the gist of it
It Just stores data you can use it for anything
sure its gonna be one of my options which iam exploring right now
gonna learn starting with playerprefs
ty for help
I want an enemy to go to the nearest point on a sphere around the player then try to stay on that circle and while on the circle shoot the enemy, the last part is easy but I'm not sure how to find the nearest point on a sphere
how should I begin this?
I think if I get a line from the player to the enemy then subtract the radius I can get a good target point
You can just use "Random.InsideUnitSphere * radius" and update that every frame the player moves for a random position
i have an assignment and im contemplating where to put the difficulty value of the game
Is it best practice to put difficulty value in game manager? or in a static class of sorts?
The plan is to use that value when I start the game in the game manager.
and the value can be changed from a ui list button
well the point should not be random
Actually, the random position should not be updated every frame, instead it should get updated when the enemy reaches the target point so it chooses another point in the sphere.
Oh nearest point, sorry I misread
Game Manager with difficulties from SO
that's okay, do you know how to find a point on a line x distance from the enemy
I think just move towards the player and when it is a specific distance away from it, stop moving nd start shooting
If you just move the enemy towards the player it will create an invisible "range" around it when you think about it
what is SO?
Scriptable Object
ScriptableObject
Thanks!
each difficulty SO for me has different values
Also
for these terms
would this still apply if im loading the difficulty from a json file?
Well, I found results for "unity so"
json works too
if you have a json with the data you don't really need SO
Although they were very sparse so I dunno
okay thank you 😄 Have a nice day guys 🙂
can ayone help me out, im trying to make a server browser for steam but every time i go inot the lobbies it doesnt show in the scroll view it spawn ages away
#archived-networking prob
no its got nothing to do wiht networking
steam/ lobbies is not networking ?
what is this video supposed to show ?
so you outta show both the inspectors for each object involved and the scripts. otherwise its all speculative.
so that where the content is
then thats the "lobby" spawning at 1500 pos z
when the prefab is set to pos z 0
cheers
is there a way to calculate the total degrees required to rotate towards something
I'm using the rotate towards method but that step thing is a pain, it's not exact so the enemy will always be a little off
i have been using the keyword " new " all the time i just dont have any idea what does it do
or mean
It means you're creating a new instance of the object type
For example, Vector3 is just a class object. You can think of it as a blueprint/template.
When you want a Vector3, you use the new Vector3(...)
float singleStep = rotateSpeed * Time.deltaTime;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);
transform.rotation = Quaternion.LookRotation(newDirection);```
how do I get single step to be the exact rotation required?
at the moment in under or overshoots
Get the angle of the direction in radians using "Mathf.Atan2(targetDirection.y, targetDirection.x)" and set that as the singleStep's value
thanks alot
Actually, I might be wrong here
Test it and see if it works
If it doesn't, use Vector3.Angle() instead. It gets the exact difference between the 2 positions
Do you mean newDirection overshoots? It wouldn't make sense for the singleStep to over/undershoot
Yeah I was thinking the same because the last 2 params in RotateTowards are "maxXDelta"
So it should just be the upper bound
RotateTowards is guaranteed to not overshoot so if it doesn't work I assume the problem is with the sprite or model not having its forward vector pointing to the right place
!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
Why not just look it up or Google it?
normally i would, however the community here forces you to engage with them 🦧
i like the community here 🦦
my unity is stuck what do i do?
you're expected to do at least some researching/googling yourself before resorting to asking
my sincere apologies
Kill it, if this reoccurs the chances are you have an infinite loop somewhere
The infinity loop bandit strikes again!
im not running any code it got stuck when recompiling
were you trying to enter play mode?
nope
Do you mean when you focus back to unity from your IDE?
in that case check the !logs
no just saving all code in vs
you're still gonna have to kill the process, hopefully nothing will be corrupted
That's what I meant. You are in your IDE, then you click (focus) back to unity . . .
are you in debug mode in VS ?
it recompiles after saving you dont need to focus back to unity for it but yeah
i exited it
after trying to attach but it doesnt solve anything
I wonder if there is an artifact still locked by VS, try closing VS, it may free up the Unity process
Oh, unity automatically recompiles when you save from VS? Try closing VS and reopening it. I didn't know that . . .
it does, but only when the VS instance is attached to a Unity instance
i killed the vs instance unity is still blocked, interesting bug
indeed, seems like some kind of race condition, I fear kill Unity is the only solution
i can just kill the unity instance and get the backup scene right
you had unsaved changes?
yeah
Hi, how can I increase the size of this window in Visual studio?
what is this window called? idk what to search for basically
That window is called "IntelliSense" or "CodeLense" though im not sure ive heard of a way to resize the prediction list it shows
Why? Just scroll...
ah ok, thanks
looks big enough in the screenshot but is hard on the eyes
becomes smaller with this theme for some reason, I'll just change back the theme
Ok
dont think that works on the suggestion box
I'm new to unity, what exactly does FixedUpdate() func versus Update()?
Fixed runs every physics step, Update runs every frame.
So I assume I can change the physics update rate?
You can, technically. It's not something you normally would need to/want to do.
Fixed is fixed on 60fps to have accurate physics? doesn't it?
50fps by default
what do you mean "what about update?"
show the update method u have currently
btw its prob because my pivot is at the feet and yours at the center, all you gotta do is remove the Y from world pos
void Update()
{
Plane ground = new(Vector3.up, Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if(controller.isGrounded && _velocity < 0f)
{
_velocity = -1.0f;
}
_velocity += _gravity * GravityMultiplier * Time.deltaTime;
if(_velocity < -53f){
_velocity = -53f;
}
if(Input.GetKey(KeyCode.LeftControl)){
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Confined;
if(ground.Raycast(ray, out float distance)){
Vector3 worldpoint = ray.GetPoint(distance);
var dir = (worldpoint - transform.position).normalized;
transform.forward = dir;
}
}```
that's the part that should matter
everything else is just movement stuff
Vector3 worldpoint = ray.GetPoint(distance);
you're still using local variable
you never writing the variable you made
remove Vector3. should be worldpoint = ray.GetPoint(distance);
from that
but anyway it will still slightly rotate cause ur pivot is in the middle of player and not like feet like mine
yea alright did that
yea it does the thing now
so from here how would i make it just twist on the y and nothing else?
worldpoint.y = player.position.y;
var dir = (worldPoint - player.transform.position).normalized;
player.transform.forward = dir;```
Why are you setting the y direction to a world point
wdym
ya that should be
worldPoint = ray.GetPoint(distance);
worldPoint.y = player.transform.position.y;
var dir = (worldPoint - player.transform.position).normalized;
player.transform.forward = dir;```
myb
i think
Yes
Or if you don't want y, as it seems, just set y to 0 in the direction
sorry I didnt take my caffeine yet xD
ay yeah I think meant to 0 out that and mixed it with the second
hey so i want to have it so while a bool is true then it heals you every 2 seconds
how would i achieve that
Update or Coroutine
how do i make sure the coroutine doesnt fire again beofre the previous one finishes
store it in a coroutine variable or make bool
Coroutine healingRoutine;
void Healup()
{
if (healingRoutine != null) return;
healingRoutine = StartCoroutine(Healing());
}
private IEnumerator Healing()
{
while (healing)
{
//Heal
yield return new WaitForSeconds(2);
}
healingRoutine = null;
}```
and i assume the healing is the bool to say you are healing right
its only to keep it running
and healingRoutine is a coroutine variable?
yes
@amber spruce you prob dont even need coroutine var you can just check if(healing) return; out the StartCoroutine func
void Healup()
{
if (healing) return;
StartCoroutine(Healing());
}
private IEnumerator Healing()
{
healing = true;
while (healing) //set healing to false to exit
{
//Heal
yield return new WaitForSeconds(2);
}
}```
this is hella inefficient
PlayerHealth playerHealth = GetComponent<PlayerHealth>(); btw
cache it once
doing that in a while loop is just as bad as doing in update
yeah ik but im only really gonna use it once for healing thats it
but you call it every 2 seconds
fixed it
If i used,
obj = GameObject.Find(“Checkpoint”)
dis = Vector3.Distance(transform.position, obj.transform.position)
When there are multiple objects called checkpoint, what would happen
it would return the first one it came across
ugly way to find objects don't do it this way
better alternative, have the checkpoints already stored in an array
could've googled that exact phrase
Hi, here are the script of each pipe object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeMoveScript : MonoBehaviour
{
public float moveSpeed = 5;
public float deadZone = -45;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.position.x < deadZone) {
Debug.Log("Pipe Destroyed");
Destroy(gameObject);
}
transform.position = transform.position + (Vector3.left * moveSpeed) * Time.deltaTime;
}
}
And here the script of the spawn of these pipes :
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PipeSpawnScript : MonoBehaviour
{
public GameObject pipe;
public float spawnRate = 2;
private float timer = 0;
private float lastPipePosition = 0;
public float heightOffset;
public float diffOffset;
public float acceptedOffset;
// Start is called before the first frame update
void Start()
{
spawnPipe();
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer += Time.deltaTime;
} else
{
spawnPipe();
timer = 0;
}
}
void spawnPipe()
{
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
float newPipePosition = Random.Range(lowestPoint, highestPoint);
Debug.Log(newPipePosition - lastPipePosition);
if (Mathf.Abs(newPipePosition - lastPipePosition) > acceptedOffset)
{
newPipePosition = lastPipePosition + Mathf.Sign(newPipePosition - lastPipePosition) * diffOffset;
}
lastPipePosition = newPipePosition;
Instantiate(pipe, new Vector3(transform.position.x, newPipePosition, 0), transform.rotation);
}
}
I'd like to change the moveSpeed of the pipes each time I pass trhough the middle of them the same way I do it for the score but as the pipes are instantiated multiple times due to the spawn function I don't find a good way to do it.
The detail of the code is not really important I just want to know how to change the moveSpeed variable each time I trigger the bird in an other script for all pipes (past and future so they all change the same at the same time)
For the score I do it with a tag but here it doesnt seems to work, I also tried with a list but I don't think its a good way to handle this and it didnt work anyways
Sounds like a job for the flyweight pattern https://refactoring.guru/design-patterns/flyweight I would have a singleton that holds the relevant pipe data like speed and have the pipes read their speed from that one central place. That way if you increase the speed variable of the singleton all pipes will read the new value
any idea whats the theme used here?
no code question
you can ctrl K, then ctrl T choose the theme
how do i post code here?
!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.
thanks
public class Flashlight : MonoBehaviour
{
public GameObject flashlight;
public bool isOn;
public Enemy enemy;
// Start is called before the first frame update
void Start()
{
isOn = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
if (isOn == false)
{
isOn = true;
flashlight.SetActive(true);
enemy.sightDistance = 20f;
}
else
{
isOn = false;
flashlight.SetActive(false);
enemy.sightDistance = 0f;
}
}
}
}
im getting a nullreference error both lines with enemy.sightDistance in them
how would I fix it?
enemy is null
where you assign enemy
how do i assign enemy
Probably in the inspector
You have to assign it on the Flashlight script
should there be a place to assign it?
There should be, that's odd
If you ctrl click "Enemy" in the flashlight script it shows you the Enemy MonoBehaviour right?
You don't have a custom editor?
I use visual studio
I meant a custom inspector
you don't have one, but yeah I don't know what could be causing this
Did you change the file name of the Flashlight script?
no
try restarting unity maybe?
how do i add something (like webGL support) to an editor version?
huh??
its there!
yeah
i spent atleast an hour trying to figure that out 😭
and it was just a restart
No idea
updated unity hub, still no option
screenshot your complete hub window
You're trying to add it to a project. Open the installs page.
and the editor has to have been installed through the Hub, if not then you can't add modules to it
my bad
Thx helped a lot
but it didnt show the option
im gonna install a new version and add it to that
and then remove this old and bugged version
how would i program a game object to add itself to an array in the editor instead of at runtime
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); works for me
so i can copy and paste that and it should work i dont have to change anything
pretty sure but there might be better ways
it should work for now thanks
If anyone could give me pointers on how to approach this possibly let me know 🙂
I have this object (hollow circle)
and depending on the amount of cuts I ask for it creates separate objects
1 cut gives 2 objects
2 cuts gives 3 equal objects etc.
The more I think about it the more its like a pie chart with equal values
but I do want to seperate them with spacing so it looks like a simon says button board.
anyone have any pointers? 🙂 thanks!
Edit: found this tutorial
https://www.youtube.com/watch?v=9fgZ286pPcY&t
but if anyone has anything to share im keeping my post 🙂
Anyone know why my models Y rot in the inspector is behaving as a -Z rot?
You can look at the docs for the method they provided. It'll have an example . . .
Hey folks, how can I use Random **not **to select a number between two choices, but rather one of the choices themselves? (Similar to random.choice in python)
Did you import it from blender?
make an array of your choices then use
int i = Random.Range(0,array.Length);
val = array[i];
Yeah, I made the rig for it
Thanks
how would i program a game object to add itself to an array in the editor instead of at runtime
