#💻┃code-beginner
1 messages · Page 434 of 1
the only thing I can think of is if the model doesn't have lightmap uvs so it does a goofy (it's a toggle on the mesh if you want to generate them, otherwise you have to bake your own into UV2/UV3)
Hi guys, I have a question about inputs. Im making a racing game where the player can quick restart the level pressing the R key. When I do this, I want the game to detect that Im still holing the accelerate key (W, in this case). Ive had a poke about online and cant see how to achieve this, would anyone know how?
At the moment, I hold accel, i go forward. I reset, not letting go of accel, and unity doesnt detect an input on relaoding the scene
i hope this makes some sense
consider manually resetting the scene objects instead of reloading an actual scene
I deleted some projects to free up memory but it didn't work. All projects have this problem. Did I accidentally change a setting without knowing it? Does anyone out there know how to drop 60FPS startup to 2 fps out of nowhere? Everything has peaked. Suddenly everything went up.
Yes this would solve it
It is a very long way around though
If its the only way then ill have to do it I guess
there is extra work but its worth it imo
if you're used to doing things like object pooling its not that much different resetting states
Im a very beginner so stuff like this is new and confusing
But im willing to give it a go
give it a shot, take note of what exactly changes in your scene and put it back how it was
I guess Ill set up a restart event in my event manager and then ask everything its original state, then go back to that on the event stary
yeah a static event could work too
what would that entail?
if you want to make easier as beginner you could replace it for a UnityEvent and do everything in the inspector
as long its on a manager type script as you said, should be present in the scene
Im not sure I completely understand, but sure I think ill give that a go
I am surprised that the input manger system doesnt have this capability by default tbh
[SerializeField] private UnityEvent OnGameReset;
internal void Update()
{
if(Input.GetKeyDown(KeyCode.R)) OnGameReset.Invoke();
}```
But I suppose it has limits
then just make a Resetting() type of method on whatever you want
and plug in the inspector
I havent used seralized fields before
Ill read the documentation to understand what you did
Thank you very much for your help
Okay I see
Im trying to get my layers numbers using theLayer.value but it returns these numbers.....
Laptop thermal/power throttling could have that effect. #💻┃unity-talk is likely more appropriate, since this probably isn't a code issue.
That looks like theLayer is not a layer, but a LayerMask
it is
how can i convert layer mask to its order number?
Yep so it's normal to see it like that. Layer masks are bit fields, where each bit of the value represents a layer.
It printing 512 would mean the 9th layer is active (2⁹ = 512)
When declaring data types, the format is usually:
public/private dataType identifier
Is there a data type that allows me to call a script? I'd like to do it so I can assign the script in the editor, similar with:
public GameObject exampleObject
Is there anyway I can do this, or do I have to specifiy the name of the script I want to call as the data type?
Specify the name of the class you'd like to reference. Eg public Thing thing; if you have your own class Thing : MonoBehaviour script file
You will be able to drag-drop the script, or an object that has it attached in the Inspector
no clue, theres no rotation code there.. and no camera reference
The force might be too low. It will move the rigidbody, but so little that the physics engine calculation will register "phantom forces" that will make it rotate around
50 isnt enough?
Increase the force, in the Inspector. The value you set in code is overwritten by the one you set in the Inspector
It might be at 1 in there
okay it works now for some reason
but the force is too much the rigidbody just teleports lol
No idea how to instantiate a prefab
Wrong spelling? Did you mean to refer to the foreach variable hand?
when i just join the game and do nothing the camera autotmatically starts rotating downards???
the camera is a child rn
if that changes anything
The object is falling on its side. Constrain the rigidbody so it cannot rotate around X or Z
It's an option you can activate on the Inspector of the rigidbody
ah
allright, how do i get the camera to turn with the mouse?
yk like an fps
if its more complex than just a few sentences then ill go reasearch it
obligatory: use cinemachine
what is cinemachine
Usually the horizontal rotation is reflected on the rigidbody, and the vertical rotation on the camera. This way the rigidbody doesn't rotate with your vertical mouse movement.
Yes it is fairly complex if you haven't done it before
are there any coding things that i should avoid when starting my first big game
Find()
the biggest thing to avoid is not understanding the fundamentals. if you understand what you are doing then you'll know what does and does not work
spaghetti
Changing variables values in ScriptableObjects thinking they'll be saved for the next play session is a common one
im an italian with the amount of spaghettification i have in my code
i know better now lol
i am not sure what that means
all good.. means ur not using them in the first place most likely
You haven't touched that feature yet, you'll be using them in the future
why?
using lerp the wrong way.. https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
also i cant find this in packedge manager
Because it is very slow and there is never a reason to use it
It searches every object in the scene for something matching a NAME, which is very brittle too
allright
the Find methods are slow because they typically have to search the entire hierarchy. there are almost always better ways to get a reference to another object
its under Unity Registry
i dont think i have that side-menu
its probably in the top left corner as a dropdown
found it
yeah
i don't think thats what i was trying to do tbh
Ah they finally changed how this looks? The old dropdown is just so unintuitive lmao
im so confused rn lol
GameObject prefab;
Instantiate(prefab, position, rotation);
unity 6 flex
that change plus the change that allows ctrl clicking to select multiple packages to queue the installs makes the package manager super nice to use now
Start with specifying what you're trying to do.
i just want to instantiate this prefab rn
i used alot of static variables in my last game which made stuff alot easier but is bad i heard
What is the reference to it called?
Keep in mind the name of the asset is irrelevant here
Ah yes, the hassle of waiting 5 minutes for each package to uninstall finally goes away
Still missing a custom project template editor though...
Unless that was added too
maybe someday 🙏
In what context
Generally just NOT static variables though
i use them to acsess values between scripts
using proper references. do not use static just for easy referencing, that will lead to the same thing that happens when you cross a black hole's event horizon
why is there some guy at the bottom
Note that Hariedo (who made this) doesn't even include statics as an option haba
Well, that is the pfp of the person who made it
He has a BUNCH of these
i see
you don't need to actively avoid static. you just need to make sure you are using it when appropriate. for example, using it to access a variable on another object is not the appropriate way to use it. Using it for a variable that is not used for any specific instance of an object and has no need to be an instance variable would be an appropriate time to use a static variable. or implementing the singleton pattern (though this pattern is also often abused by people not understanding how to get a proper reference)
Am I right about using Cloud Save client sided could cause problems such as the client using cheat engine to modify values? I don't know how cheat engine works properly, but I keep looking for ways to make the save & load server sided but it's too complex for me at the moment, am I safe to go with clientsided?
Depends on the game and what you are trying to protect against. The game your pfp is from shipped with built-in cheat codes 😛
You can't really prevent state modification without running the simulation on a server.
I guess I'll just use clientside till I know how to do server side then
are they all up somewhere? (would be useful if I need to post something for others)
I just find them on UDC and save them haha.
I'm sure he would share them if you asked though!
I am procedurally generating a mesh at runtime. How do I draw that mesh without creating a meshrenderer?
To render a mesh you use a MeshRenderer
Or use Graphics.RenderMeshXxx
how do i round a float in unity without using Mathf.Round? im also converting to a string if that helps
if it's just for the string, you can use a format string
Graphics.RenderMesh() this for the 'Graphics.RenderMesh' doesn't exist
and RenderParams rp; for 'RenderParams doesn't exist'
Make sure to look at the correct version of the unity documentation that matches your Unity version
I'm using the following code to make an object chase/home in on another object. When the chasing object gets close, there is a noticable increase in speed. Additionally, if the target object has no collision, the chaser will pass over the target (as is expected), but will also maintain its course and begin moving away from the target object. How do I stop both these issues from occurring?
playerPos = new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z);
direction = playerPos / (playerPos.magnitude);
direction.Normalize();
rb.velocity = Vector2.zero;
rb.AddForce(direction * moveSpeed);
This doesn't make any sense
First of all, why not just
playerPos = target.transform.position;
Second of all, your direction calculation makes absolutely no sence
You're dividing a position by it's magnitude
direction is generally handled with a subtraction operation
https://docs.unity3d.com/540/Documentation/Manual/DirectionDistanceFromOneObjectToAnother.html
Instead of doing
directon = (targetPos - myPos).normalized;
Look up vector math
And well, think logically too - a direction spans from point A to point B and your calculations only included variables coming from point B. Read your code carefully next time and analyze it + learn how to debug values to know what's going on
does anyone know why , im not movind when im using the new input system? i added the Move method as an event to well Move InputAction
You are reading from the variable move, not from the ctx parameter
moveDirection = ctx.Read
Oops I forgot mbmb
But it still doesn't really work
i forgot to put the GetReferences() method in start
smh
why not just make the change that was suggested?
and if it is still not working then, then you probably haven't enabled the input action(s)
Wait, why are you setting moveDirection in update now? That is further from the suggestion I made than what you had before
Also, we have no idea what GetReferences is of course.
Perhaps share the whole code instead of screenshots
which collider2d should i use for a path in a tower defence game
moved MoveDirection into update cause it was the only idea that i thought would work
Well, did you try what I said? It would have been JUST changing the word move to ctx
Also, stop doing screenshots
Why the path needs collider to begin with?
When im placing towers i need to check if theyre colliding with the path
i did and it didnt work
No
Be mindful, if someone requests your code as text, don't send a screenshot!
Use whatever collider that fits the path
Box collider most likely
That was only part of the issue. Put it back to read from ctx
Do i add several box collider components to the one object?
many tower defence games use a grid based system and not colliders at all but if you really need that, I'd use PolygonCollider2D and Collider2D.OverlapPoint to check if the point lies inside the collider
hi, someone know what to do if string reference it doesn't appear? (There is a key)
https://paste.ofcode.org/CMLRzZLZy9MvBrwcBEtHDD heres the playerMovement script as well
I thought the polygon collider would work but it doesnt it looks really weird when i add it and doesnt fit the path
It's auto generated with the delaunay triangulation but you can also edit the collider yourself or even create it from scratch afaik
Several on one or separately, doesn't matter, or one Polygon collider as AleksiH suggested
I got it working by editing the polygon collider thanks
alright fixed it , it works now with how aethenosity suggested just ahd to change the default map to Player and the default Scheme to KeyBoard & Mouse
how do i make it so a raycast only detects collisions of a certain layer?
(in code)
pass a layermask into the raycast method
Raycast takes a latermask as one of its parameters
ah ok, thanks!
just a note because it can be confusing, selecting a layer in the layermask means it is included not excluded
i always forget which away around it is
Nice! Yeah, being in the wrong map can be a tough issue to diagnose sometimes. Should have thought of that earlier.
Does anyone know if Unity has somewhere that tells you the currently active map? Maybe debug mode and looking at the PlayerInput component? I'll check that next time I can
theres an input debugger
Window > Analysis > Input Debugger
Ahhhh yeah. I always forget about that one. Thanks!
also Wrong scheme! , if u made a custom scheme and set your actions to that scheme it wont work if the default scheme isnt on the custom scheme
Well good on you figuring it all out. The new input is definitely more complex, but really powerful
yeah i see that and since i found out abt the event system with the input system , its gonna be so useful so glad i fixed everything and switched to the new input system
can someone say me why my player jump so hight plz
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermov : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if (Input.GetKey(KeyCode.W))
body.velocity = new Vector2(body.velocity.x, speed);
}
}
this is my code can you explain me how to make im jump less low
!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.
csusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermov : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if (Input.GetKey(KeyCode.W))
body.velocity = new Vector2(body.velocity.x, speed);
}
}
i dont uderstand sorry
Read the bot
for how to post your code correctly
stop spamming your unformatted code
Use Google Translate
🥲
'''cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermov : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if (Input.GetKey(KeyCode.W))
body.velocity = new Vector2(body.velocity.x, speed);
}
}
'''
🤷♂️
ok my bad
You can always just copy paste it from the bot
also, you are using the same variable for jump as you are for movement speed. That is likely not what you want
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermov : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;
private void Awake()
{
body = GetComponent<Rigidbody2D>();
}
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if (Input.GetKey(KeyCode.W))
body.velocity = new Vector2(body.velocity.x, speed);
}
}
sorry 🥲 for the time i take you
speed is the velocity of your jump AND the velocity of movement
which..... seems like a poor thing to do
so wath should i change?
Make a different variable for your jump....
Simple as that
turn body.velocity = new Vector2(body.velocity.x, speed); into body.velocity = new Vector2(body.velocity.x, jumpSpeed); and also create jumpSpeed
Change the variable to how you want the jump to feel
ok thanks i uderstand i'm gonna try right now
Worth a mention that Input.GetKey() will return true for every frame that the key is pressed - there are alternatives which will only return true for the frame in which the key is first pressed/when it's released
Oh yeah, ABSOLUTELY this ^
Unless you wanna fly, use a single frame input instead of held input
like this?
thanks i solve the problem and sorry to take your time i'm new in unity and english is not my first language so...
Guys, I have no idea why I'm getting these syntax errors from this code. I know I probably look like an idiot and this is something really simple but I just can't see what wrong with it XD
for (int i = 0; i < playerLives; i++;) { Instantiate(heart, heartContainer, false); }
Errors: (26,45): error CS1026: ) expected
(26,46): error CS1513: } expected
i++; the ; isnt needed
but also that Instantiate looks wrong with the parameters
thank you so much
yeah the second parameter should be heartcontainer.transform
Hi! I need to make a dialogue system that loads the monologue one by one instead of having them load all at the same time. How can I make this happen?
ooooohhhh i want to know that too
pretty much any dialogue tutorial will show you how to display dialog line by line
thanks
Might be overkill but you can look into the Inkle unity plugin
As a starting point, at the very least it'll give you a frame of reference
hellooow
I made a turret on Blender. It has 3 bones - 1 for tower, 1 for turret head and 1 for the turret. I followed a tutorial on how to properly export the model as FBX and import on Unity. I added a sphere mesh on unity and put a script on it. The turret(the whole thing from blender) supposed to move whenever it get near the sphere but it the doesn't. On the turret, I added meshcollider with convex checked, Rigidbody, and a navmesh. Somehow, whenever I remove the bones, the addforce thing works on the turret but I added the bones for a reason and don't want to remove it. I hope someone could help me or guide me with this problem. Thanks.
Adding bones to it sounds like it would over complicate things, so just out of curiosity, what was the reason to add them?
You'd have to show your setup. A bone in unity would just mean theres a child gameobject and this would move along with your parent object (excluding the renderer parts here because not necessarily related).
Though it sounds weird that you added a navmesh to it
A lot of this also doesnt make sense like
"added a sphere mesh on unity and put a script on it"
to move or rotate the object because if there is no bone then the entire turret along the heads get knocked off or sometimes the head just move from the position and freezing the position is not what I want since the parent which is the tower is can move around using navmesh
Sorry for the confusion. The sphere represent like a blackhole. I'll show.. it.. a moment.
this is what I meant
and this is the script
using UnityEngine;
using System.Collections.Generic;
public class PlanarGravityScript : MonoBehaviour
{
public Transform atmosphere;
public float gravitationalRadius = 10f;
public float gravitationalForce = 10f;
public Color gizmosColor = Color.red;
void Start()
{
Physics.gravity = Vector3.zero;
}
void Update()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, gravitationalRadius);
foreach (Collider collider in colliders)
{
Rigidbody rb = collider.GetComponent<Rigidbody>();
if (rb != null && rb != GetComponent<Rigidbody>())
{
Vector3 direction = transform.position - collider.transform.position;
float distance = direction.magnitude;
float gravityStrength = gravitationalForce / distance;
rb.AddForce(direction.normalized * gravityStrength * rb.mass);
}
}
}
void OnDrawGizmos() {
Gizmos.color = gizmosColor;
Gizmos.DrawWireSphere (transform.position, gravitationalRadius);
}
}
and instead of the tower... I'll use this another object which has bones too but only 2 bones.
i am trying to find whats causing this error but im not sure, its the "object not set to an instance of an object" error and its this line foreach (IDataPersistence dataPersistenceObj in dataPersistenceObjects)
i think the IDatapersistence script shouldnt need to be attatched to a gameobject since its an interface not a monobehavior
dataPersistenceObjects is null
Instead of existing, dataPersistenceObjects does not
i think its too much for discord ty for putting me in the right direction
!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.
Where do you set dataPersistenceObjects to anything
the quick check is right before that line add a debug line that prints out if it is null, then at least you know to look for that specifically
you should add debugs to see whats happening. also this looks wrong
Rigidbody rb = collider.GetComponent<Rigidbody>();
if (rb != null && rb != GetComponent<Rigidbody>())
I did added a debug but the problem still persist.
Debug logs don't fix problems, they reveal problems
What did the log say?
I know. the debug won't show up
Then the code isn't running
it is running.
No. It is not
If it were running the logs would be printing
It affect other things but not the mesh with bones
If the log isn't showing up, the code is not running
You either put the log in the wrong spot, or hid logs in the console
Assuming the log messages are not hidden
I mean it logs but only when an object with no bones gets collided with it
Maybe.... show what you did?
okay.. I'll record a screen
ohh.. okay..
And maybe a ss of the console
this is my code:
using UnityEngine;
using System.Collections.Generic;
public class PlanarGravityScript : MonoBehaviour
{
public Transform atmosphere;
public float gravitationalRadius = 10f;
public float gravitationalForce = 10f;
public Color gizmosColor = Color.red;
void Start()
{
Physics.gravity = Vector3.zero;
}
void Update()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, gravitationalRadius);
foreach (Collider collider in colliders)
{
Rigidbody rb = collider.GetComponent<Rigidbody>();
if (rb != null && rb != GetComponent<Rigidbody>())
{
Vector3 direction = transform.position - collider.transform.position;
float distance = direction.magnitude;
float gravityStrength = gravitationalForce / distance;
rb.AddForce(direction.normalized * gravityStrength * rb.mass);
}
}
}
void OnDrawGizmos() {
Gizmos.color = gizmosColor;
Gizmos.DrawWireSphere (transform.position, gravitationalRadius);
}
}
Where is the log?
a moment... it's compiling my code
Pro tip: always remove logs and other debug information in your code, so that people that help you can't guess what you have tried.
nice sarcasm
I meand the Debug.Log line of code...
The thing being asked for, and necessary for us to help with
I can see this code failing with compound colliders.
what is that?... I have no idea what is compound colliders.
just used unity 2 weeks ago.
It's when a collider has an rb in one of the parents.
https://docs.unity3d.com/Manual/create-compound-collider.html
https://docs.unity3d.com/Manual/compound-colliders-introduction.html
yeah... that's it. the root has rb and mesh collider
why does my 3D Audio Settings not play when im in the range of it
I thought at first it was the navmesh causing this problem but it turns out it's not
sorry man.. I can't help. I'm a newbie.
same
I'm also asking for help here.
Is that code related? If not then #🔊┃audio
ok
Can anyone help me, I've been trying to see this code I made for 1 day because it's not going
it should appear in the inspector to be able to place the GameObjects but it doesn't appear, and this error appears
Assets/scripts/MudarCena.cs(24,12): error CS1520: Method must have a return type
!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.
Your method has no return type. Simple as that
Look at every other method you have, and then the one on line 24
Compare line 12, 18, and 30 (which are correct) to 24
Do not crosspost (which includes directing people to other channels)
#📖┃code-of-conduct
#854851968446365696
bruh literally nobody has responded tho
Absolutely irrelevant
yes ok, I will look at the problem and see if it solves it
stfu lil bro
Whelp 🤷♂️
<@&502884371011731486>
lol snitching ahh
"whelp" 🤓
!warn 1160004646115475536 Don't spam the channel. Listen when people point out server rules.
apechasers has been warned.
Ah, I see I was correct to not answer you after I saw you spam your question twice in two minutes
bro deadass thought he did sum pinging a mod
Glad to see I'm still able to detect problem children before engaging
bro deadass your cringe as fuck
!mute 1160004646115475536 3d ignoring warnings, spam
apechasers was muted.
I was gonna go answer there before the emotional breakdown
"Ahh" "cringe" "deadass"
Oof
They have a bunch of stickynotes with various one word slangs that can combine in various ways to get their thought across.
A markov chain trained at an elementary school
Bible quote and gorilla tag clone link in their description and skibidi/toilet as pronouns.
Quite the collection haha
how do i make a method that kills (setActive(false)) the player wait until an animation is finished?
if someone answer pls ping me in the message so i can read it,ty!!
Does it have to be a method? If yes, then a coroutine(though it needs to run on an active and enabled object) or async method.
Otherwise a timer in update.@radiant frigate
it doesnt have to be a method, im using a coroutine because of the properties that enables waiting, but any way that works is alright, and how do i make the timer if i dont know how long the animation is?
Ah right. If it's waiting for the animation, animation events could be used. Or checking the animator for the currently playing state.
could you explain it again pls? i didnt understand it
What part of it?
this message
Surely you understand at least some of it..? It's in English.
how can i make it wait for the animation?
i understand the words but i dont understand what you mean with them
that's what the message explains: animation events or checking the animator state.
I am using the Navigation System, but want to know how I can adjust the pathfinding. I am making a TD game and don't want all the spawned Enemies to follow the exact same path. Currently I am using the agent.SetDestination() function.
If you need more control over the path, you can calculate the path via the Navmesh and then do whatever you want with it. Obviously, you'll need your own agent/controller to move the characters.
Are there any videos on this topic? I have been searching but might not know the keyword I need for this.
I would like to dive deeper into the topic
I don't think so. You'll need to read the docs and figure out a way that works for you.
Though it's not that difficult. The only actual navmesh related thing that you need to do is NavMesh.CalculatePath, though there are a few more functions that could come in handy for modifying the path correctly. That basically gives you an array of points.
From this point on, it's not realted to navmesh at all, you can move your character however you want along these points.
Anyhelp is fine. Thanks for this 
How to change Terrain's material thru code?
unlike meshrenderer, name.material does not work
how can i make a music slider that changes the value of an audiosource? my approach is to make a static audiosource and change its value to equal the slider one, but how could i reference the audisource?
I heard that tasks aren’t really supported in webGl, but specifically multiple threads, i think
Would using await and then a custom task.Delay work? (Like using task.yield and time.time) Since some people say that it’s only Task.Delay that doesn’t work
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
have you looked into the audio mixer? It'd be easier to change the volume of that
but yea audio mixer is the more proper way to handle volume for sounds
not sure if the handles of audiomixer is exposed in the editor tho
ty all!
Hey! Trying to learn about how graphs work, but my script seems off. It's always printing "Left Click Value : False" regardless of if I have my right click button held down or clicked. Any ideas?
public InputActionProperty leftClickAction;
public Animator cubeAnimator;
void Update()
{
bool leftClickValue = leftClickAction.action.ReadValue<bool>();
print("Left Click Value: " + leftClickValue);
}```
I've tried using it as a bool and using it as a value, neither of which seem to work.
{
if (ItemSlots[i].transform.childCount > 0)
{
Debug.Log("Deleting item: " + ItemSlots[i].transform.GetChild(0).GetComponent<Item>().ItemData.Id);
Item item = ItemSlots[i].transform.GetChild(0).GetComponent<Item>();
DeleteItem(item);
}
}```
What am I missing? I have 24 ItemSlots, only one which contains an Item, but if I trigger this function it triggers 10 times on the 1st and only item id?
Try changing int i = 1 to int i = 0
Make sure that the slots are assigned correctly. Debug the slot name.
shouldn't that also be throwing out of bounds unless your collection si actually 1 indexed
This, which is why I suggested chaning from 1 to 0
yeah but he also need sto change i <= to i <
Also not sure why he isn't just using foreach here
{
//for (int i = 1; i <= InventoryData.ItemCapacity; i++)
for (int i = 1; i <= 28; i++)
{
GameObject slot = Instantiate(inventorySlotPrefab, transform);
slot.name = i.ToString();
ItemSlots.Add(i, slot);
EmptyItemSlots.Add(i);
}
}```
the collection starts at 1
I had a foreach, but had the same issue, thought the regular for might fix it
What is ItemSlots?
private Dictionary<int, GameObject> _itemSlots = new Dictionary<int, GameObject>();
What's your reasoning behind using a dictionary this way
pretty sure this is one of those situations where I'm doing something extremely stupid, but just don't see it
what does that have to do with it?
it's tracking which items are in which itemslot
Stepping through the code with a debugger might provide some clues. As well as confirming the objects in the hierarchy.
let me try
Also, it snot really clear where those logs are coming from. I don't see them anywhere in the shared code.
Ah, ok,I see the deleting one. But what are the others?
This might be a silly question
I added the itemslot name like someone suggested
But did you check that your item ids arent duplicated?
Maybe share the whole relevant !code correctly as we're just getting confused over nothing
yes
📃 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.
Might also get more usable information by moving the debug out of the conditional so that it tells you what it did on each itemslot, that way you can check the overall flow
ah found the cause, the function is just getting called several times because the event is thrown on Item
which throws it for each item in my game -_-
Alright fixed it 🙂
Moved the trigger to my Inventory and added a check to see if it's already deleting everything
Thx for the assist
public class detectShoot : MonoBehaviour, IPointerClickHandler
{
public GameObject flashPrefab;
public GameObject muzzlePoint;
private Rigidbody2D rb;
public Rigidbody2D playerrb;
public void OnPointerClick(PointerEventData eventData)
{
GameObject duped;
duped = Instantiate(flashPrefab, muzzlePoint.transform.position, muzzlePoint.transform.rotation);
Destroy(duped, 0.250f);
}
}
can i use void Start() in this case? i wanna define rb of the duped object using getComponent
cuz defining it in the OnPointerClick will probably be more calculation thus lowering fps
Don't quite understand the question. There's nothing there that wouldn't work in Start(), however you probably need to reconsider your overall structure because it's very unclear what you're trying to do
Is your goal to just have muzzle flash whenever a shot is fired?
Because in that case you should just be enabling/disabling the muzzle flash, not destroying and instantiating it
how so?
If you have very high rates of fire with this approach it's going to become incredibly inefficient
its getting duplicated after the 0.25s of animation is finished
Because instantiation is expensive
this 'define rb of the duped object using getComponent' makes no sense
nah, its a farm gun used to shoot aliens. the player is a cow
You are constantly having to compute gameobjects being created and destroyed, as to it just dissapearing and reappearing
How the fuck does that relate
a cow cant shoot fast 😂
wait imma try record and show you the exact problem
The gun fires a bullet and has a muzzle flash
can the gun ever be firing more than one bullet at a time? No
Therefore there should only ever be one muzzle flash at a time
I'm trying to swap materials to a specific object via script, the materials are made from a custom shader.
I have an "issue" where when replacing, unity generates instances instead of using the original so I fail to check if the current material is the same as the new one
Here's the code: https://pastebin.com/rKtZtc5s
Is this due to the fact that I assign the materials to handle in new temporary variables?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Does the muzzle flash ever change in terms of position? Also, no, it's always attached to the end of the barrel
That's subjective.. There should only be one muzzle flash at any given time, you should just make it appear and dissapear. That's a lot of extra computing for no reason.
Therefore, it's logical to just have a single muzzleflash attached to the end of the gun so you never need to worry about manually positioning it, worrying about rotation etc
IF you needed many objects, like lets say for bullets, then you also would never do it this way, you'd create an object pool and recycle the bullets as they leave the screen or otherwise expire
Great what's your issue here
This isn't really relevant
Besides instantiating, what extra info does that give us 🤣
we're not saying your way doesn't work, just that it's an incredibly inefficient way to do it
the muzzle flash
its doesnt look good when it stays in one place and the player falls down
yes
because you're setting it up wrong
that's what we're talking about
Do an animation then perhaps
Just have a single muzzleflash and attach it to the transform
so i wana set the velocity of the muzzle's rb to the player's rb
Why does it have a rigidbody
the muzzle is a different animation. cant make one for all stats the cow can be in
The muzzle should not be a rigidbody
Because if the cow is falling and he shoots the muzzle flash will follow it if it doesn't.
Just take off the rb and child it to the transform
Use a particle system perhaps?
it'll follow the rb of the cow
This is like trying to control a swarm of agents by just giving them all the same orders and hoping they stay synced
its just a theory i want to test
The issue is he doesn't want that style where it FOLLOWS the gun front
i tried 4 hours to make a good looking one that fits my game's style. unfortunately i am not Dani 😦
its doesnt look good when it stays in one place and the player falls down That sounds exactly like what he wants to me
i just want it to fall down with the player.
IT Doesn't look good WHEN it (the flash) stays in one place.. And the player falls down.
I'm taking that as it being locked to the front
That makes zero sense
the rigidbody is just an idea
try this
so i create the instantiate as a child of the gun?
Don't instantiate anything
Just do it in the editor
Create your prefab, drag it to where you want it positioned and child it to the gun sprite
add a reference in your script
Where you're normally instantiating, enable it and where you're destroying, disable it
also disable it in Awake or Start in case you forget in the editor
That causes issues when you fire fast though..
what difference would it make? faster processing ?
Why would that cause issues? You can't fire more than once per frame
and this isn't a minigun
Dawg
but the animation is 3 frames
Clearly there is more than 1 flash on the screen at once
is that intentional?
If you did that, it would suddenly appear and dissapear
yeh, i had that problem in a different game
It looks fine to the game design
It looked like a single sprite to me. If its actually an animation, then you probably need to just setup an object pool
but you should still child them to the gun and get rid of the rigidbody
it's really two separate issues
if i do the rigidbody thing and do flash_rb = player_rb then will it cause performance issues in reference to mobiles?
So JOC IS THIS VIDEO how you WANT it to look like or is this showing what you DONT want it to look like?
Because that's what I don't get
The video fucked me
i just dont want the flash to be lagging behind
Then it needs to be childed, however you're then going to have an issue where they overlap
You want it to be like stuck on the front?
yeh
But you also want the little fade out?
ig, cuz i cant make particle system that looks good enough
A particle system would be your best bet here I'm thinking lol
Then you don't have to deal with instantiating
wait, i will try to instantiate it as a child of the gun, if it works as i want, i will inform. if not will discuss further
i did 4 hour and the best it looked like was a 5 y.o making fireflys
Couldn't you just set it to a billboard or stretch billboard render and rotate it to the proper position, and give it that same fire shit as a material? Idk haven't worked in 2D but I could get pretty much the same system.
Hello, i'm sorry if it's the wrong channel but I've got a mesh problem.
I've got a gameobject in my scene wth a meshfilter, but the problem is that I can't get the reference of this object
i can get it by code
but when i do a getassetpath it returns null
it should returns null only if it doesn't exist
but my mesh seems to exist...
I tried to do a Search in the project but didn't find, I've found the mesh ID in the scene file but idk what to do with it
I don't think a mesh filter counts as an "asset" it looks like you are trying to find the filter rather than the mesh itself
i instantiated the object, and used transform.setParent(Gun) and it fixed it
oh THATS How you want it to work
i'm looking for the MeshFilter.sharedMesh
yeh, i am a really shit explainer
Good job
If you want to optimize it, you can look into object pooling so you aren't constantly instantiating and destroying the prefabs, but probably not a necessity at the scale you're working
Rather than instantiating maybe make 5 clones of it and activate them and deactivate them in loop o-o
the fastest firing gun i am gonna have will be a alien pistol that works like a glock maybe. so ig i wont need it but still, thanks
wouldnt that be more performance heavy?
thanks again to both of you
It's not an issue of need, it will just smooth out your performance
No
No you're just activating and disabling objects, rather then having to create a whole new one.
Instantiation is the expensive operation here
oh ohki
well imma add them to the plan cuz i am now really bored of making the player cuz i am working on it for a week now
making things look good and smooth
It's more of an optimize at every turn type of deal.. There's a lot of situations where crap hacks can solve problems, but those will start to add up. And you don't want to end up accidently using your crap hacks later on when you make a game where it matters.
Object pooling is just kind of a basic thing you need to learn with Unity, even if it isn't absolutely necessary here. People tend to ignore it (or not realize it exists) and then they go and try to instantiate 500 buttons in a ui every frame
or create a bullet hell that's actually just a stress test of your RAM
Ex. Pre line up 300 bullets, iterate through and set them to active and fire them. Instead of having a minigun that shoots like a mf and causes lag. (Again creating gameobjects is way more heavy than just working with ones that already exist)
also did u like my game design? all cows are murdered by aliens in a farm except one. that cow makes a space ship using the tractor in the farm and fly to the alien's planet and from there, its a wave surviving game
💪 Interesting
I support cows
Seems a bit odd why the cow would fly up there every time and practically kill himself with no way of winning but nice idea.
As a visual example since I had this sitting around. With object pooling you can do really, really silly things without worrying about performance too much
idk about winning, i can add it as a story so it defeats all bosses and then can have a endless mode
trying to instantiate those bullets or missiles as needed would be a disaster lol
Absolute
I've deleted EVERYTHING except the scene, but still got some meshes
i really don't understand
It could be stored in the scene itself🤷♂️
aw really ? is there any way to extract the mesh, by accessing the mesh in the meshfilter or idk
Yeah, you could save it as an asset via code.
how would you counter this kind of bug where an object with collider sometimes pushes you through the ground -.-
in this vid id didnt happen tho
Make the object move in a physically compatible way
That would make it stuck on top of the player if that's what you wish.
i dont
Then explain what kind of behaviour you want
im trying to phrase it right too :3
detect squish - kill player 😛
thanks a lot, it worked !
HEY
THIS IS A GREAT IDEA NGL ty for suggestion!!!
tbh actually why not
it is a thing that some games do, if killing the player is a normal thing in the game
killing is a part of my game :3
game design issue rather than a code one tbh. Either kill the player (though you should be careful to only kill if directly under and to add some sort of warning symbology to the ground), add an invisible wall or other gating mechanism to prevent a player from being underneath, or use a rounded collider to push the player out of the way as the elevator comes down
what shooting method should i use for ranged enemies? objects or raycast? if raycasts, how can i make it feel real
real as in that the player needs to know when the enemy is shooting or how to dodge the enemy
pls mention when replying
by object im guessing u mean rigidbody. if u want unity physics, use a rb. If u want a super fast projectile or a projectile that doesnt care about physics, use raycasts. About your question for it being real, you still would add visuals. But that part is more of a game design question instead of coding
its pixel game
here is a vid of the game
that doesnt really change anything about my answer. making it feel real is something u gotta consider in terms of game design. Like if there should be a chargeup sound/animation
maybe ask what specifically you could do for this in another channel like #archived-game-design or id:browse if that doesnt suit.
or look at what other games do, though typically its just a chargeup sound/animation as i wrote above.
oke thanks.
that could suit for large or tank type enemies, what about small enemies that spawn frequently
helllo guys I have a fps game where I have a imported a character model in which the body parts are not separable now when I try to attach hands of the player to the gun it looks fine but as soon as it jumps or runs it can see the inside of its body, for now I have just disabled player's body for local view so the gun is only there but is there any other way of doing it???
Hi guys I have a quick question. I'm setting up my game by creating the characters and their corresponding HP bars but I'm afraid I'm assigning the components in a very wonky way, especially since I'm always using .Find() (especially in lines 46-51)
Would you say this is OK or do you recommend a different way of doing this? I'm a beginner so I'm unsure whether this is the right way to do this
Here's the code:
https://paste.ofcode.org/JZGCrG4DYvQ754PCiPiFNz
What do you think?
do you think that its possible for navmeshagent to work with rigidbody?
This is not good practice, no
Can you give me hints on what you would do?
Add [SerializeField] private <Type> <fieldName>; fields for all of the components and connect them in the Unity inspector
can anyone help in this
Thanks 🙂
im trying to make a gun in 2d and the gun doesnt want to shoot only when i click it just keeps going and going and i dont know how to stop it
heres the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shooting : MonoBehaviour
{
private Camera maincam;
private Vector3 MousePos;
public GameObject bullet;
public Transform bulletTransform;
public bool canFire;
private float timer;
public float timeBetweenFiring;
// Start is called before the first frame update
void Start()
{
maincam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
MousePos = maincam.ScreenToWorldPoint(Input.mousePosition);
Vector3 rotation = MousePos - transform.position;
float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, rotZ);
if(!canFire)
{
timer += Time.deltaTime;
if(timer > timeBetweenFiring);
{
canFire = true;
timer = 0;
}
}
if(Input.GetMouseButton(0) && canFire);
{
canFire = false;
Instantiate(bullet, bulletTransform.position, Quaternion.identity);
}
}
}
use GetMouseButtonDown(0)
why is there this random blue area in game view but not in scene view any solutions ?
I would put a script on the root object of the prefab and interact with it entirely through that script
Reaching "down into" another object like that is poor practice.
hello! i am trying to reference a script called "Movement" on instantiation but it doesn't work:
=====Spawner Script=====
Movement movement;
void Start()
{
GameObject temp = Instantiate(Object);
temp.GetComponent<ObjectScript>().Function(movement);
}
=====Object Script=====
Movement movement;
void Function(Movement movementHolder)
{
movement = movementHolder;
}
is there a way to reference it in script without using the Find function?
I see no attempt to get a reference in this code to the Movement script
how do i reference it
[serializefield] private ...
i cant use serializefield bc the object is a prefab that gets created during runtime
you can on the spawner script, isn't that the idea?
and from there you inject it into the others?
Where is it relative to ObjectScript
So you recommend creating scripts for each prefab that needs initialization via script?
Im trying to make a version control collab project with my friend but despite adding them into the organization they cant seem to see the project or enter it any idea what i might be doing wrong
Ok then you have it and can pass it into ObjectScript with a function like in your example. Should work fine. But your example is not showing it as serialized so I'm confused
it is attached to some other gameobject
At a minimum.
yes i only wrote it like this as an example
i also made it serialzefield in the object to see if the value changes during playtime but it remains null
There's something wrong with how you set things up in the editor then, you'd have to show screenshots
But sharing your actual code is much better than some contrived example
Is your camera the same Z-pos as your world?
how do i change a image's width in code?
https://discussions.unity.com/t/change-width-of-ui-image-c/149486 is this what you mean?
hello, i'm trynna make my own acceleration and decceleration script for a 2d character controller. and for some reason, when i'm going to the left, the character sort of goes back a little when i release the arrow key.
What settings are on your Rigidbody
Also how is dir set?
Your condition with dir == 0 is wrong
Dir is going to be either -1 or 1 depending on which way you press
yeah but if i don't press, it's going to be 0
sooo why is the character going back when i go to the left and release the arrow key? it's working properly when going to the right
sooo what do i do?
You should be using Mathf.MoveTowards instead of this jankiness
Otherwise properly account for the direction you're moving
i tried movetowards before and...idk how it works
Because you can't just blindly add or subtract, that will only work in one direction
Your code right now assumes that deceleration is always to the left and acceleration is always to the right
soo i just can implement this?
speed = Mathf.MoveTowards(rb.velocity.x, _maxSpeed, 0.3f) * Time.deltaTime;
No
that....kinda makes sense? tho i'm still lost a little
so how?
More like speed = Mathf.MoveTowards(speed, dir * maxSpeed, Time.deltaTime * .3);
can i just do Mathf.Sign(dir) cus i wanna deccelerate instead of stopping right away
how do i make the script disabled when the scene is loaded, but then i can enable it from a different script by a function
My code is already handling the deceleration
Or rather acceleration
That's what MoveTowards does
if i were to draw the curve it makes, what will it look like?
An acceleration curve
Acceleration is constant
Velocity is linear
Position is quadratic
Depends which chart you look at
i'm talking about the character's speed
so velocity
ok ok i will try to implement this
hoenstly the line of code I shared is pretty much the entire function
the only missing part is assigning the velocity.
yeah the rest of the conditions are useless i just found out
speed = Mathf.MoveTowards(speed, dir * maxSpeed, Time.deltaTime * .3);
rb.velocity = new(speed, rb.velocity.y);```
the only other bit would be handling a different "deceleration" rate vs "acceleration" rate
if desired
so like...
float rate = dir == 0 ? .1f : .3f;
speed = Mathf.MoveTowards(speed, dir * maxSpeed, Time.deltaTime * rate);
rb.velocity = new(speed, rb.velocity.y);```
How so?
that should depend on your rate of change in movement . . .
yeah yeah i landed on 50 for acceleration and 70 for decceleration, so i'm good now
just need to make the code look better cus it looks like it's made by a beginner which i'm definitly not
im tyring to do a script that allows the player to pickup rigidbody objects, yet it doesnt work.
its able to detect when im pressing on an object that has a rigidbody, but then it cancels
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Bump
is there any way to edit single mesh renderer characters?
ps. I have a character and I want to detach my characters hand from the body but it has only one mesh so I'm not sure hot to do it
cant
youll need to open it in blender or smth
you can use the animation tool to move the hand but it wont detach, only stretch
guys i have a mouse position code that converts the mouse position to vector3 and its literally doing nothing does anybody have any ideas?
here is the code:
public Vector3 GetMouseWorldPosition() { return camera1.ScreenToWorldPoint(Input.mousePosition); }
- it's three backticks for code blocks, not just one. you'd think after the number of times you've made this mistake you'd get it at this point
- "literally doing nothing" isn't very descriptive
- https://unity.huh.how/screentoworldpoint
- true i just dont have backticks on my keyboard so i always highlight and select the code thing
- more descriptive: i made the Vector3 public to see what it was doing and it wasn't updating the Vector3 at all
- i'll have a look
what Vector3 did you make public? because you aren't assigning anything in the code you showed
that is a method not a variable. it can't appear in the inspector
public Camera camera1;
public Vector3 GetMouseWorldPosition()
{
return camera1.ScreenToWorldPoint(Input.mousePosition);
}
private void OnMouseDown()
{
mousePositionOffest = transform.position - GetMouseWorldPosition();
}
private void OnMouseDrag()
{
transform.position = GetMouseWorldPosition() + mousePositionOffest;
}```
i did it
as in code block
not the thing lol
have you actually confirmed that any of these methods are actually being called
oh never knew that
does IObjectPool has a "safety check" method?
What happens if somebody returns an already destroyed object? 🤔
why would you be putting destroyed objects into your object pool?
you shouldn't, exactly 😅
I want to know if there is a safety check or just a cryptic crash the next time you get that item from the pool 🥲
I guess I could crash myself on the Release action 🤔
ah...
tried debug logging and no they are not
If you are pooling, why would the object ever be destroyed?
i dont see how though?
you can check for yourself: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/ObjectPool/ObjectPools.cs
the answer is no, you need to be handling your pools correctly to ensure that you aren't doing something dumb like putting destroyed objects into it or destroying the objects already in it
human error 🤷♀️
I am pooling gameobjects, I can see one of my boys attaching the GO to a parent, destroying the parent, then returning the object (the object got killed by the parent)
Are they on non-UI objects in the scene with colliders on them
good ol' asserts will do then!
Thanks!
to test i was using the only object on my scene which is a backdrop but it isn't a UI object its just on its own but it also doesn't have a collider
i'll get just a square hold on
It has the same safety check that other destroyed objects do: You'll get an error in the console, the function will end prematurely, and the game will otherwise continue to run in it's best capacity despite having bad data in memory somewhere
So, it probably won't blow up your entire program, but it's also definitely not something to try to test the limits of
just remembereed either way my script isn't telling me my MouseWorldpoint or even registering im clicking
i have an idea hold on
not UI
doesn't have collider
well no wonder OnMouseDown wasn't being called
i might be using the wrong input system
it still isn't lol
if you are using the Input System rather than the input manager that would also be a reason why it isn't being called
use the event system interfaces like the IPointerDownHandler interface
nevermind im using public voids so that wouldn't make sense either
i have tried that once but i'll try again
this is irrelevant if OnMouseDown is not being called
i also have another idea but im not sure if it would work, if i used if statements would it work?
if statements aren't going to magically make OnMouseDown be called if the conditions for it being called are not met
That depends entirely on the what and the where
nah ik but
btw it worked
what worked
well instead of using that void OnMouseDown() i did an if statment in the void Update() but doing the exact same thing and its now updating the moueposition
which i know also means instead of picking something up this will instead make it teleport to the mouse but that works better for what i actually wanna use it for
holy shit wait
fixed everything its all done everyone here kiss me i'd like to thank my family, friends and the people who helped me along the way
https://postimg.cc/N5ZQYkrP
What am i doing wrong?
This is a stupid question, and I understand somewhat insignificant but hey, this is the beginners section...
Does it make sense to name a script "SceneSystem"? I want the script to be ran across all scenes, and I want it to only be responsible for loading different scenes when triggered by events? I know SceneManager is already taken by Unity, and "LevelManager" per TaroDevs tutorial doesn't seem like a fitting name for my project
if it's responsible for loading scenes then i'd use SceneLoader since that's its intended behaviour . . .
Oh, yeah that's a better name. Thank you 🙂
Cross-posting
I didn't know where to post
Good class to make a singleton, right?
also, you can use SceneManager, just create your own namespace
namespace Immortal
{
public class SceneManager : MonoBehaviour { }
}```
honestly, be defeault, you should use (have) your own namespace. this prevents conflicts between your classes and others' . . .
if you need to access it from any scene, then yeah . . .
I was just learning about namespaces, but I'm hesitant to misuse them somehow. Could a general rule of thumb be to basically just follow my folder structure? For example I have SceneLoader saved to Scripts>Global, would Global be a good namespace?
...stupid questions get smart answers, you've already taught me more than I expected, thanks
dope
"global namespace" is usually no namespace at all, which means, structures can be accessed from anywhere. If your folder is called Global, you might consider not creating any namespace
I suppose, not many people, including me, create their classes in namespaces in Unity. So, your PlayerController, GameManager etc. usually don't refer to any namespace
When having another functionality, for example, a full assistance scope, which should not interfere with the main game management, I would consider creating a new namespace. But this is just my opinion
I don't tend to use namespaces at all personally. Granted, I do use Assembly Definitions, which is also a form of code compartmentalization, but I don't tend to use custom namespaces in addition to that
That makes sense. macro-micro, as things get smaller, their influence should shrink
Bump
Right, as an example I would like to provide an example for namespace management:
The main game with a player - global namespace
The editor-only functionality for this game - namespace UnityEditor (built-in)
A mini game to get cool bonuses - namespace MiniGame
A level creator for the main game - namespace LevelCreator
Is it impossible to get a component of a gameObject's component set in editor, in the Start function of a script?
Ahh okay makes sense!
It is possible if it's public. Otherwise, reflection
I think you're asking if you can call GetComponent in Start? Yes, you can
Gotcha
I suppose, they are asking whether it's possible to get a component's variable, whose type is Component
Sorry I literally meant if calling GetComponent was doable in Start
I'm a bit dense in the head forgive me
Of course you can call GetComponent in start.
If it's on the same object, may as well do it in Awake
Aye aye
how do i make the script disabled when the scene is loaded, but then i can enable it from a different script by a function
Is it in the scene to begin with or spawned in at runtime
Uncheck the box next to the script on the object
thanks bro
it was that simple lol
Yep, a disabled script can still be referenced and enabled like any other, it just means Unity functions like Start and Update don't work, but you can call functions manually
thats exactly what i was going for, cause when i tried disabling the script by this.enabled = false; in the first line of the Start function it didnt work and the function was still called
Awake is usually better for something like that. Of course the rest of the method that it is called in will still execute. (Disable in start and start will still run)
But yeah, when possible do it via inspector
yeah i just realised i have to change it to awake cause when i disable the function and then enable it again the start method doesnt run
Yeah, start (and awake) only ever execute one time in the objects entire lifetime
There are OnEnable and OnDisable though, which run EVERY time it is enabled or disabled respectively
this what i was looking for
thanks
Bump x3 
are you asking why text messages are limitied in size?
No, why is text ends abruptly?
It should go to the next line once it reaches the "end" of parent?
But it's just goes to the next line whenever it wants
@muted narwhal Don't cross-post, instead provide more information in #📲┃ui-ux so it can actually be answered.
If someone wanted to answer they would ask me for more information?
I'm sittin' there for 5 hours
No-one is going to engage with fishing out information out of you. If you want question answered provide information.
pretty simple really, draw it out on paper first so you stay true to it
draw what exactly
the process of coding a state machine?
or the states i want to create?
a state diagram circles and lines
oh no idea whats that, i need some research
i mean
i know what are diagram circles and line but idk how exactly a state machine works
i just know i need it rn
can be as simple as a case switch statement
using System.Collections.Generic;
using UnityEngine;
public class moveScreen : MonoBehaviour
{
Rigidbody2D rb;
public float speed = 5;
float inc = 0;
void Start(){
rb = GetComponent<Rigidbody2D>();
}
void Update(){
float inputx = Input.GetAxis("Horizontal");
float inputy = Input.GetAxis("Vertical");
Debug.Log(inputx);
Debug.Log(inputy);
while(inputx > 0 || inputy > 0){
inc = inc + 0.1f;
}
rb.velocity = new Vector2(inputx * (speed + inc), inputy * (speed + inc));
}
}
anyone know why this is causing my code to crash (it started when I implemented the inc value)
nvm I'm foolish
infinite while loop
a while loop is pretty inappropriate here anyhow
what's the intent with a while loop here
a loop inside Update is going to finish entirely within a single frame.
When you want something to happen over the course of several frames, Update itself is the loop you want
to constantly check if my inputx or inputy is more than (or eventually less than) 0 so I know when the palyer is moving
Update runs every frame
ah
you don't want or need an additional loop
so if would be better
I don't see what the poiint of "inc" is at all
so it's hard to say
it doesn't make sense
make the movement faster the longer you move for
but you're never resetting it
I was gonna reset it after I finished implementing the speed increase
I would expect something like:
float inputx = Input.GetAxis("Horizontal");
float inputy = Input.GetAxis("Vertical");
Vector2 input = new(inputx, inputy);
if (input.magnitude > 0) {
inc += Time.deltaTime * acceleration;
}
else {
inc = 0;
}
rb.velocity = input * (speed + inc);```
what's .magnitude
the magnitude of the vector
I pretty much did that
just minus the whole time.deltatime * acceleration
That's a very complicated if statement
it works tho
Also you're missing deltaTime which you will need if you want this to be consistent at different framerates
oh ok
realistically this code should live in FixedUpdate too
what's the difference
I'll google it actually
I forget google is a resource sometimes
fixed version of update, wow
how does this work?
isn't comparing a vector to an int not possible?
or is that only for vector3
we're comparing input.magnitude. it's how big the vector is
input is a vector, input.magnitude is a number
that makes sense, thanks
magnitude is a scalar value
There's plenty of tutorials on learning maths for gamedev, but why and where is this maths actually useful? Here, I try to give examples of how and when different types of mathematics pop-up, and how they are actually used when making a game. I have added links throughout the video and below if you want to learn these topics in more detail, but ...
fun watch
I'll save that for later
omg i'll save that
wouldn't it be in the animation channel
not really, im not animating anything for this thing i'm trying to code
its literally three squares
probably game design then
void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
StartCoroutine(CreateOrModifyMesh()); // alters triangels, such as hiding a face
}
void Update()
{
UpdateMesh();
}
private void UpdateMesh()
{
mesh.Clear();
mesh.vertices = verticies;
mesh.uv = uvs;
mesh.triangles = triangles; // is this when drawcalls are made?
GetComponent<MeshCollider>().sharedMesh = mesh;
mesh.RecalculateNormals();
}
Is this a valid approach to making a dynamic mesh and the comment about drawcalls is that correct?
Also should I semiphore the updateMesh call to ensure the createOrModify step is fully completed?
draw calls are made when the scene is rendered at the end of the frame
GetComponent<MeshCollider>().sharedMesh = mesh;
This is not necessary to do every frame
should I semiphore the updateMesh call to ensure the createOrModify step is fully completed
Maybe? It's not clear what that coroutine does in the first place.
It essentially builds the array of verts, triangles and uvs, I would also in that process do things like remove hidden faces
What's the relationship between that and your UpdateMesh function?
Why does UpdateMesh run every frame?
Are you expecting everything to change each frame?
is there a difference between state machine and finite state machine?
Finite State Machines are a subset of State Machines.
I was thinking if the triangle array changed not in size, but in values I'd have to reassign it, but I suppose I wouldn't have to per what you're saying
Well first off are you expecting that to happen?
but no, you don't have to do that
The renderer already knows which mesh to render
THis is basically a minecraft style chucnk of voxel that I coudl "dig" into
There's no reason to run UpdateMesh every frame
You only need to run it when things change
runing it every frame is wasteful
Makes sense, I was thinking if the traingle data changed, but now that you say it sounds legit
mesh.RecalculateNormals() I assume would be a good thing to call in the updateMesh
yes in UpdateMesh, but not in Update
thanks much for the insigfhts
is there a way to load the chronological last scene in the build settings?
Use https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneCountInBuildSettings.html then load that number - 1
thank you so much 🙏
Guys how can i get a list or array of all objects colliding with a boxcollider?
OnCollisionEnter
then add to the list..
OnCollisionExit -> check if its in the list -> remove it
ill try it thank you
yo i wanted to make a shooting script for 2d but the player just keeps shooting and doenst stop even if i click my mouse and i wanna make it shooti only when i click can anyone help me
thats the code
!code use formatting or paste bin for big code blocks like so
📃 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.
alr ty
so i just edit it and put that?
kk i fixed it
If you're using a paste site, make sure you select C# highlighting
Right now it's just a white wall of text
wym like the ``cs?
No, it should be somewhere on the paste site
A drop-down with all language highlightings
public float sensY;
public Transform orientation;
float xRotation;
float yRotation;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRotation += mouseX;
xRotation += mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.rotation = Quaternion.Euler(xRotation, yRotation, 0f);
orientation.rotation = Quaternion.Euler(0f, yRotation, 0f);
this is my camera controller that i made form basic tutorials and such, but when i move my mouse down it looks up how do i invert that
i thought i just had to swap smt but i been testing stuff out and i am NOT gettin it
if + number goes one way a (-) number will go the other way
Not every single one may have it tho, not sure
soo just negate the value
alr ty 🙏
https://paste.ofcode.org/JQNKsdJ2esZM7NryCnsnP4 does this one work?
Yep
alr ty
First of all, check the value of timeBetweenFiring
how would i enable and disable hide in editor for a variable on the fly?
And try to debug what's going on, place a Debug.Log where the timer get's cleared and where the bullet is fired
its set to 100 rn cause i was playing around with it but before all this it was set to 1 and both shot at the same speed
Also
With a custom inspector or a custom attribute . . .
Is there any error in the console?
none
like, if i check a bool then another variable appears in the editor
this isn't needed but it'd make it a lot easier to manage
Then place the Debug.Logs to see what's going on
You would need to create a custom inspector script
or use an asset like NaughtyAttributes or OdinInspector which both have that functionality
im like really knew to this so how do i do that
Debug Log should literally have been the first line of code you ever wrote in Unity
any resources on how to do that?
You could, for example, google it
there's documentation pinned in #↕️┃editor-extensions
mb
But basically, Debug.Log("hello", gameObject); would print "hello" in the Unity console and clicking the log would point you to the specified gameObject
Second param is optional
But useful
So basically I have a ready function but I want it to be activated on a trigger. But I want the script to check if the player is touching the trigger of ANOTHER object and not the the object where the script it. How do I refference it?
Have a reference to the thing with the function on it, and in the player's OnTriggerEnter, detect when you hit the object you're looking for call the function on the thing that you referenced
in my code i have the sprint set up so when you hit a button switches your state to sprinting yknow simple enough, but how do i go about making the increase in speed not instant and like a increase over time thing
like instead of just goin straight from 5 to 10 the number would gradually increase over a second or two
is it a complicated thing or is there a simple way to do it
Hi, when i use my arrow keys to move my rigid body, it moves forward but when i use the exact same rb.addforce() when a button is clicked, it moves sideways, how do i fix such
take the speed value and lerp it up and down to the speed u wish to use..
Lerp, or SmoothDamp, or MoveTowards, or some other method..
if(running){speed = (Lerp to Run Speed);}
.. then farther in the code
movement * speed
alr ill try workin that in
i use 3 speed variables..
desiredSpeed
walkSpeed and runSpeed
i set desiredSpeed to be one or the other.. (w/ smoothing inbetween) and just use my desiredSpeed in my Movement function
cant be.. if its the same force and same direction it'd act the same
do i not also have to state a time for acceleration or smt to tell the interpolater how fasts its going?
yes. that'd end up being an extra variable u can fine-tune to make ur player adjust its speed faster or slower
alr thank you
i call mine momentumSmoothing
Having a problem where bullets hit multiple enemies when theyre close together even though they are scripted to be destroyed upon colliding is there any fix?
2D
using UnityEngine;
public class SmoothMovement : MonoBehaviour
{
public float walkSpeed = 2.0f;
public float runSpeed = 6.0f;
private float desiredSpeed;
public float momentumSmoothing = 10.0f;
private float currentSpeed = 0.0f;
void Update()
{
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
desiredSpeed = runSpeed;
}
else
{
desiredSpeed = walkSpeed;
}
currentSpeed = Mathf.MoveTowards(currentSpeed, desiredSpeed, momentumSmoothing * Time.deltaTime);
transform.Translate(Vector3.forward * currentSpeed * Time.deltaTime);
}
}
``` something like this
after like 4 errors i got it working well enough for me to take it from here thank you this example really helped
rb.AddForce(transform.forward * verticalInput * speed) <- player script
rb.AddForce(transform.forward * 1 * speed) <- button
well, are they oriented the exact same?
transform.forward could be two different directions dependin on its transform
I'm looking for a way to clamp or constrain a vector to another vector with some variation
so like if a character is facing forward, I want to move a vector towards something, but only so much
and if the character turns that vector would be able to turn with it
When you say "move a vector towards", do you mean rotation or displacement?
wouldnt that just be a local Rotation?
{
// The step size is equal to speed times frame time.
float singleStep = rotationSpeed * Time.deltaTime;
if (constraintVector != Vector3.zero)
{
// Get the angle difference from constraint
float angle = Vector3.Angle(targetDirection, constraintVector);
float rads = Mathf.Max(maxDegrees - angle, 0);
if (showLog) Debug.Log(angle + " R " + rads);
// Convert to radians
rads = (rads * Mathf.PI) / 180;
//Debug.Log(angle + " R " + rads);
singleStep = Mathf.Min(singleStep, rads);
}
Vector3 newDirection = Vector3.RotateTowards(startVector, targetDirection, singleStep, 0.0f);
newDirection.y = 0;
//Debug.DrawRay(transform.position, newDirection, Color.red);
// Calculate a rotation a step closer to the target
return newDirection;
}```
the issue I have now is that it doesn't work as I intended, if the target direction is too far outside it just completely stops rather than keeping up with the contstraint vector
im already using that
What when you debug transform.forward and the force you are inputting, what does it say?
Show the console for it
the issue is I need the max rotation to depend on how far its already angled away from a target vector
I thought I had the solution but I didnt
and now im lost
Yes its the same object
forward shows 1
🤔 debug the values u use like Aethenosity asked
I need the blue vector to be able to move within the red cone defined by the red vector, while being clamped inside when it gets to the edges of that "cone"
So, you need some sort of smoothing, where the further away you are from it the faster it goes?
Alright ill do that
no I Need it to be clamped within an angle of another vector, while trying to rotate towards the target as far as it can
I have an enemy which basically can look around, but can also rotate its model
I want it to look quickly but rotate slowly
and not be able to look directly behind itself
I tried getting the angle between the desired rotation and the constraint/red rotation, but I haven't found a way to properly use it
I need the max radians to basically find how much it can move until it hits the "border" of that max angle from its base
is the cone vector thing 2D?
yeah so like
have you looked at vector projections or vector components?
no
I dont think that works for this
imagine like a tank and the red vector is the direction of the base vehicle
and the blue is the barrel
the barrel can move faster, but can only rotate so far relative to the base
so, it's an actual 3D cone? and you have the red vector and you only want to move the blue one to (for example) 15 degrees or the red one if it goes above 15 degrees?
yeah I want it to be constrained within x degrees of the red vector when it tries to move
like how you can move your head quickly but can't look behind you
you can only move your head so far before you need to turn the rest of your body
but I can't find out how to get the "max radians delta" based on the red vector
you can probably do something like getting angle between the 2 and if it's above X, you subtract from the angle you got, you get a cross product of the 2 vectors and you rotate around that axis with that subtracted angle (or minus that angle, I can't math that well 😄 )
X, if the angle is above X
that'd be the amount you need to bring it back
oh...
or...
if angle above X, you get that cross product and rotate the red vector X degrees around that axis
well, that'd be to get the constrained blue
I'm not saying to actually move the red one, just rotate it X degrees around that axis - that's where blue should be
Is there a way to scale the game to different screen sizes properly?
I have tried ways but they all increase / decrease the distance between objects or zoom super in or out which affects gameplay.
I want each player to have the same experience