#💻┃code-beginner
1 messages · Page 554 of 1
thanks
A kinematic rigid body exerts forces but does not respond to them. A kinematic rigid body moving through a field of boxes with normal rigidbodies will push them aside, but not be slowed down by them. This makes it useful for characters that are being directly controlled so you can interact with your environment without losing any sense of control over the character.
How to set GameObject variable the "GameObject" that the script is in?
This.gameobject
thanks bro
i need help with a attack script on a dummy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
[SerializeField] private float moveSpeed = 7f;
private void Update() {
Vector2 inputVector = new Vector2(0, 0);
if (Input.GetKey(KeyCode.W)) {
inputVector.y = +1;
}
if (Input.GetKey(KeyCode.S)) {
inputVector.y = -1;
}
if (Input.GetKey(KeyCode.A)) {
inputVector.x = -1;
}
if (Input.GetKey(KeyCode.D)) {
inputVector.x = +1;
}
inputVector = inputVector.normalized;
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
Debug.Log(moveDir);
Debug.Log(inputVector);
transform.position += moveDir * moveSpeed * Time.deltaTime;
float rotateSpeed = 10f;
//transform.forward = moveDir;
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
Debug.Log(transform.forward);
}
}
I have Doubt in this code , When i use
transform.forward = moveDir;
it reverts back to (0,0,0)
but when i use
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
it does not revert back to (0,0,0)
You shouldn't need to set a GameObject variable to this GameObject since you always have access to it . . .
yes makes sense
im just a little confuse and trying to ge the hang of it but i get it now
No problem. Any script derived from MonoBehaviour has access to the gameObject property. It is the GameObject the script is attached to . . .
thx man
How to use a method from a script to another script?
make your method public and inside the script you want to access the method you simply create a reference to the script that holds your method.
how to creat that reference?
[SerializeField] Scriptname scriptname; //assing the script via inspector and you can acces the method with
scriptname.yourmethod()
thxxx
hello, i am trying to add a pause menu using dotween
public void OnPauseButtonPressed()
{
isPaused = !isPaused;
Time.timeScale = isPaused ? 0f : 1f;
if (isPaused)
{
pausePanel.SetActive(true);
blockingPanel.SetActive(true);
pausePanelRect.DOScale(originalScale, animationDuration)
.SetEase(Ease.OutBack)
.SetUpdate(true);
}
else
{
pausePanelRect.DOScale(Vector3.zero, animationDuration)
.SetEase(Ease.InBack)
.SetUpdate(true)
.OnComplete(() =>
{
pausePanel.SetActive(false);
blockingPanel.SetActive(false);
});
}
}
the pause works, when i unpause animation plays but then panels are not deactivated and timescale doesnt change, any idea what im doing wrong?
first and easiest thing would be to log the isPaused boolean.
see if it behaves as intended. you could also use debug log inside the if statements to see if these are being reached
How can i make it so in a 2d game, the camera smoothly follows the player. When i directly change the x and y position of the cam to the one of the player, it's shakey, even when using SmoothDamp. When in the scene, i set the camera to inherit and follow the player, it doesn't shake but i cannot control the lag the camera moves to follow the player
How would i go about it?
make sure you're moving the camera in LateUpdate, after the player has moved
yup, that was the saving grace not the offset, thanks
check under the General tab from the pinned messages . . .
you're trying to set the camera during the same frame the player is moving. there is no way to determine if the camera or the player Update runs first. LateUpdate runs after every Update, ensuring the player has finished moving before updating the camera . . .
Hello everyone.
While my code does work, I'm seeking a more elegant solution.
My code thus far:
initialPanel.transform.GetChild(1).GetChild(0).GetComponent<Button>().interactable = hover;
initialPanel.transform.GetChild(1).GetChild(1).GetComponent<Button>().interactable = hover;
add.transform.GetChild(1).GetChild(0).GetComponent<Button>().interactable = hover;
add.transform.GetChild(1).GetChild(1).GetComponent<Button>().interactable = hover;```
Sure, I could add separate GameObjects to each button but it's worth mentioning that I'm also performing operations on the button's (gameobject's) parent:
```cs
infoPanel.SetActive(true);
initialPanel.SetActive(true);
add.SetActive(false);```
So I would have 5 seperate GameObjects. Surely there must be a better way?
(the first .GetChild(1) fetches the parent of the button)
Oh noooooooooooooooooo
ik im sorry 😭
Indeed
You should just refer to them directly
[SerializeField] private Button fooButton;
As an example: if you're making a little popup dialog window, you might have this
public class PopupWindow : MonoBehaviour {
[SerializeField] private Button okButton;
void Awake() {
okButton.onClick.AddListener(Close);
}
void Close() {
Destroy(gameObject);
}
}
the window would also have methods to actually..show text to the player, of course
gotcha
there is no way to determine if the camera or the player Update runs first.
script execution order
So why would you advise only doing half the job via the inspector? What's wrong with setting the onclick event there as well?
In this case, you might as well just add the listener in the inspector, yes
But then there would be no need for a Button reference at all 😉
and the example vanishes in a puff of logic
unless you need to modify it's properties, like in my case
True. You're setting the interactable property there
that's manually forcing the order; by default, there is no determination . . .
Anyhow, thanks. I'm trying to keep my code clean before it's too late 😆
In general, you should prefer explicit references
If you're instantiating a prefab, give it a component that holds the references you need
and reference the prefab as that type, rather than as a GameObject
You'll often start out with a dumb "bag of references" that later gains its own functionality
you should not manually set the order for all of your scripts to ensure one starts before the other . . .
On top of that, using LateUpdate in general is bad design
The whole point of LateUpdate was actually for the camera, but imagine if something else now requires to be executed after the camera
It's strict and cumbersome to work with. Better to make your own system of invokations if you need to invoke in order
It is useful as a "post-animator" step
I suppose I do think way ahead with the whole "don't use LateUpdate" remark but I really dislike when something is limiting my code like that
I run stuff there (with a very late script execution order) so that I can access the positions of objects once animation and IK have been applied
tbh i never had any case where i had to use LateUpdate
I only really run a "ticker" component whose sole job is to tell other components to run
I also have to make sure Cinemachine updates after this, because I need to move some targets into their final positions
it's a dependency graph!
game logic <- animator updates <- IK <- spline manipulations (i have splines whose knots are parented to things that are animated) <- camera update
I am working to get rid of evil stuff, like embedding packages solely so I can edit their script execution orders
(and replacing that with manual execution)
So uh, @swift crag , is this better? 😭
[SerializeField] private GameObject infoPanel;
[SerializeField] private GameObject initialPanel;
[SerializeField] private GameObject add;
[SerializeField] private Button properties;
[SerializeField] private Button delete;
[SerializeField] private Button element;
[SerializeField] private Button compound;
[SerializeField] private TextMeshProUGUI title;```
instead of accessing each child
Ideally "infoPanel" and "initialPanel" would have custom component types on them that hold more references
I tried using Panel but unity game me the finger. It's an UI element, perhaps it's just an image
"Panel" isn't a component type
it's just one of the "templates" you can add through the GameObject menu
Sorry 😭 A bit rusty after a year long break
I used to think panels were somehow special :p
Ok yeah got it to work now
Thanks again
Alright. It's Christmas Dinner time. I wish you merry christmas and no bugs in your games!!
hi, im making a doodle jump clone and i want to add spring and jetpacks on certain platforms. i want the jetpacks to be rarer than the springs, so i made their chances to spawn 2.5% and 5% respectively. however when i roll a random number to spawn them, if i roll a jetpack, it's already smaller than the spring's chance so it will spawn both of them on the platform. how can i fix this?
If all of the odds add up to less than 100% (as one would hope), you can subtract each one from the result and see if your random value is now less <= 0
so, for example: if your random value is 0.06 and the first chance is 0.025, you subtract that to get 0.035
this is more than zero, so that event doesn't happen
then you subtract 0.05 for a 5%-chance event, giving you -0.015
this is <= 0, so this event happens and you stop
(in your case, you could say you have a 92.5% chance to not get anything)
this is if you are choosing a random choice
if instead, they are separate events, you would use 2 random values for each event, leading to a 0.125% chance to get both
There's more than one way to make this happen, and some cleaner approaches, for a quick an dirty fix you can approach it like this without changing much of your initial code. But there's a mathematical problem with this.
public void AddGoodies(GameObject spawnedPlatform)
{
float random = Random.value;
GameObject thingToSpawn = null;
Vector3 spawnPosition = Vector3.zero;
if (random < (springChance / 100))
{
spawnPosition = spawnedPlatform.transform.position + new Vector3(Random.Range(-spawnedPlatform.GetComponent<SpriteRenderer>().bounds.size.x / 2 * 0.8f, spawnedPlatform.GetComponent<SpriteRenderer>().bounds.size.x / 2 * 0.8f), spawnedPlatform.GetComponent<SpriteRenderer>().bounds.size.y / 2, 0);
thingToSpawn = spring;
}
if (random < (jetpackChance / 100))
{
spawnPosition = spawnedPlatform.transform.position + new Vector3(Random.Range(-spawnedPlatform.GetComponent<SpriteRenderer>().bounds.size.x / 2 * 0.8f, spawnedPlatform.GetComponent<SpriteRenderer>().bounds.size.x / 2 * 0.8f), spawnedPlatform.GetComponent<SpriteRenderer>().bounds.size.y / 2, 0);
thingToSpawn = jetpack;
}
if (thingToSpawn != null)
{
Instantiate(thingToSpawn, spawnPosition, Quaternion.identity);
}
}
The problem with the approach you have is if spring has 5% and jetpack has 2.5%, but they use the same random number. so 5% of the jetpack is always gonna be result to spring to spawn so it's equal to not spawning the spring which in reality decreases the chance of the spring the spawn by the possibly of the jetpack which will result to 5 - 2.5 = 2.5 so spring will also have 2.5% chance to spawn in reality.
btw you should probably store spawnedPlatform.GetComponent<SpriteRenderer>().bounds.size in a variable, it'd make the code a lot more concise
sorry, im a bit confused with this approach, what is the point of "jetpackPosition"?
Even better: spawnedPlatform should be a Platform, not a GameObject
you'd create a Platform component that can tell you where a spawned item should go
so that this code would never touch a SpriteRenderer at all
Oh I forgot to adjust it one second.
hi
whats the easiest way to paint on a 3d object?
are you asking how to do this at runtime (in-game) or while creating assets for your game?
I fixed the code ^^
Instantiating needs a position to spawn the object on, we make a temporary one (Vector3.zero) and then assign the actual value if we the condition is met to spawn the thing.
at runtime
// Write black pixels onto the GameObject that is located
// by the script. The script is attached to the camera.
// Determine where the collider hits and modify the texture at that point.
//
// Note that the MeshCollider on the GameObject must have Convex turned off. This allows
// concave GameObjects to be included in collision in this example.
//
// Also to allow the texture to be updated by mouse button clicks it must have the Read/Write
// Enabled option set to true in its Advanced import settings.
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Camera cam;
void Start()
{
cam = GetComponent<Camera>();
}
void Update()
{
if (!Input.GetMouseButton(0))
return;
RaycastHit hit;
if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
return;
Renderer rend = hit.transform.GetComponent<Renderer>();
MeshCollider meshCollider = hit.collider as MeshCollider;
if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null)
return;
Texture2D tex = rend.material.mainTexture as Texture2D;
Vector2 pixelUV = hit.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
tex.SetPixel((int)pixelUV.x, (int)pixelUV.y, Color.black);
tex.Apply();
}
}
i tried this from the docs
but is not working, and i checked everything
no errors, but is not painting
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
Wouldn't this would suffice the functionality you want?
GetComponent<Renderer>().material.color = theColorYouWant;
that would tint the entire material
you should do some basic debugging -- check if the resulting pixel values make any senes, for example
If the texture isn't read/write enabled then this won't do anything
i enabled that
Ah right.
Though are you using urp, hdrp or built-in?
hm i dont know, how do i check that?
i only changed the to hurp one because everyhing that i imported was pink
i think i need something here
you may have installed the HDRP package, but that wouldn't do anything on its own
(and you should not be trying to switch render pipelines on a whim!)
ok, i was about to mess things up
Hi all. What is the best way to pass around an object of a plain c# class to modify it from other scripts?
just...pass a reference as usual?
you can't serialize a reference in the inspector because your class is not a kind of unity object, of course
pass it normally, like an argument in a method . . .
if you want to pass it in the inspector you can make it a scriptable object
should other scripts modify it, or call method on the enclosing script (where the C# instance exists) to modify it?
Like say I have a monster class and create monster1 in a script. I want to access that monster1 instance from another script. I'm asking what is the way to do it.
what is "another script"?
are you talking about components attached to game objects here?
MonsterManager to increase or decrease health for example
I don't understand why you're asking this question. You give the object to whoever needs it
Maybe you're trying to figure out how to find the second component..?
the one that needs to be given the monster object?
why not just a Health component on each of your monsters?
Monster is not a kind of unity object
yeah nope. Its just a c# class. I got a bit confused here. I'll come back once I figure what got me confused 🙂 thanks
guys can somebody help me with this. i actually have no idea how to stop this flipping effect
hey how do I make a pause in the middle of a loop
alright thanks
theres no way its this hard
I'm having issues with MonoBehavior.OnGUI. If I take an snippet from the official documentation, Unity only renders button shapes and complains with "Can't Generate Mesh, No Font Asset has been assigned"
I think I'm missing a setting here, but I've searched for a bit and can't seem to find where I could specify a font
I had a problem with this on my Steam Deck
for whatever reason there was just..no font
I wound up stuffing this into an OnGUI method
if (!fontInitialized)
{
GUI.skin.font = font;
GUI.skin.GetStyle("Toggle").font = font;
GUI.skin.GetStyle("Label").font = font;
fontInitialized = true;
}
where font is a field holding a Font object
thanks a lot, this fixes my issue, I wonder why he is not able to reach the default font
I'm not sure why it happened on my Deck either :p
How can move a gameobject that have a rigibody kinemactic?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingThings : MonoBehaviour
{
public GameObject Target2;
public float WaitTime;
public GameObject Target;
public float Speed;
// happen at game start
void Start()
{
}
//Constant load
void Update()
{
{
{
//everything that has a wait time
StartCoroutine(Wait());
}
IEnumerator Wait()
{
for (int i = 0; i < 10;)
{
//moves to point 1
transform.position = Vector3.MoveTowards(transform.position, Target.transform.position, Speed * Time.deltaTime);
yield return new WaitForSeconds(WaitTime);
//moves to point 2
transform.position = Vector3.MoveTowards(transform.position, Target2.transform.position, Speed * Time.deltaTime);
}
}
}
}
}
why isnt it going back and forth between the 2 game objects
MoveTowards does not happen over time, you need to call it each frame for the duration of your move. also you're starting the coroutine potentially hundreds of times
MoveTowards computes a position that's closer to the destination. That's all it does.
PingPong would go back and forth
It does not, inherently, cause something to slowly move
what would I replace Move towards with then
Perhaps you want to repeatedly move towards the target until you're close enough
you're only moving once, which doesn't make any sense
void Update()
{
float time = Mathf.PingPong(Time.time * Speed,1); // value between 0 - 1
transform.position = Vector3.Lerp(Target1.transform.position,Target2.transform.position,time);
}``` maybe pingpong w/ lerp is what u want..
im just basing it off of
> why isnt it going back and forth between the 2 game objects
Yes that is exactly what I wanted thank you
is it allowed in the rules to post a snippet of code i dont understand how it works and someone explaining it?
because i just followed a tutorial for a fps camera controller and i have no idea how it works
You can, but if watching the tutorial it's from wasn't enough to explain it, I'm not sure how anyone can help by reiterating it. But you can try.
alright thanks
{
lookleftright = Input.GetAxisRaw("Mouse X") * sensX * Time.deltaTime;
lookUpDown = Input.GetAxisRaw("Mouse Y") * sensY * Time.deltaTime;
xRotation -= lookUpDown;
xRotation = Mathf.Clamp(xRotation, -90, 90);
transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
}```
i followed a brackeys tutorial for this and im not really sure whats going on, and also the rotation on the y axis is not working
where i get the input?
don't multiply mouse input by deltaTime, it is already frame rate independent so by doing that multiplication you end up with stuttery camera controls that are dependent on the framerate again
sry it is actually right
got it thanks
as for why rotation around the Y axis isn't working, that is likely due to you not actually rotating anything about the Y axis currently
oh and when removing that multiplication you'll need to reduce your sensitivity variables by a factor of like 100
so should i add a transform.localRotation = Quaternion.Euler(0 ,xRotation, 0);?
no because that would be incorrect
why don't you pay attention to the tutorial and find out what the tutorial expects you to do for rotation around the Y axis
alright
found out the problem, thanks
but the single thing i dont understand is why the xRotation -= lookUpDown;
because you want to accumulate the rotation so that it can be correctly clamped, so it has a variable that stores that accumulation which you then add or subtract the mouse's up/down movement to actually perform the accumulation
if you are only learning it is fine but if you plan to implement it into your game you should probably look into the new input system instead
where can i investigate that
there's documentation pinned in #🖱️┃input-system to learn how to use it. if you are just starting out and following tutorials, then just stick to the tutorials. though you would be much better off by following a structured course rather than random tutorials made by people who barely know what they are doing
does anybody here code malbolge like me?
this is a unity server with no off topic allowed
just wondering
thats not off topic
this is a channel about coding and i asked a simple question
it's an esoteric language that has nothing to do with unity. it is off topic.
i mean both of em use code so i dont know the problem
has nothing to do with unity
also could you teach me c#
no, there are beginner c# courses pinned in this channel
alright thanks
ey can someone help me out ? im trying to show the name/tag of every game object. currently im iterating through every gameobject in the scene with a foreach loop and outputting it to the screen with w2s and a gui label, but its EXTREMELY laggy because of how im iterating through every single game object every frame. is there a faster way to do this?
idk how else to get every game object without just iterating through every single one
you could simply cache the gameobjects in an array or list of gameObjects.
what are you trying to achive actually
idk, im just messing around with this singleplayer game out of curiousity.
woulddnt i still have to iterate through it with a foreach loop?
modding discussions are not permitted here
I have a base class called "Ability". With my knowledge at the moment, if I were to make a new ability, I would have to create a whole new c# script to define a new ability that extends the "Ability" base class. Sounds alright for now, but what if I wanted to define 5 new abilities? 10? 30? 100? The amount of script spam in my project just for abilities seems like it would be intense. Anyone have a better idea on what to do here?
well it depends, if these abilities do the same thing but with different stats, then it's just a matter of reusing the same objects and assigning different stats to them. but if they need different behavior then yes, you will need to write new code for that behavior. this is expected
it is also not "script spam" to have many scripts that do different things. that is how it should work
Makes sense. I suppose if I were really concerned about my organization, I could put all these abilities into different folders
you should write new code when you do a fundamentally new thing
"Abilities" are a very common pain point -- you want to re-use many aspects (like "shoot a projectile" or "affect an area"), but it can be very difficult to make these behaviors reusable
maybe just different types of abilities with different stats. For example AoE with different radius and damages. Then point and click abilities with different ranges and sizes
Your mentality about the situation is good, but I don’t think it matters if you have 100 different ability scripts. The only problem with that is probably organizing them. Performance is nothing to worry about with that. Literally makes no difference. But you also could just make your 100 scripts messy and it wouldn’t change anything about your game either.
What we are comparing here is the difference between a well organized project and a not organized project.
One of which will allow you to make changes or add new abilities in a much easier/efficient way subjectively
you could create all your abilities in one script, and then reference them from that script
What I would do is categorize all your abilities into notepad find out how many of those abilities are actually performing different actions, which is probably only like 5-10 from the 100 abilities.
Then you can make scriptable objects for each ability with like an enum that points to which “type” of ability it is so it can attach the correct script to it.
But there will always be new code that you will need to write for each ability. So what’s the point or creating only 5 scripts for 100 abilities and scriptable objects? Simply to make “adding” a new ability easier. That’s it
Okk
Anyone use a global EventBus or just rely on C# events?
https://hastebin.skyra.pw/qevoqeveqa.pgsql why does this not work ?
the object its supposed to hit has a collider and has the tag fuel onn it
have you configured that code is actually running?
after you confirm it runs, double check your parameters
the raycast functrion doesnt work i tried debugging it was showing
please re-read my messages again
the code is running
okay so now read the second message
yea i double checked
so you think the parameters are correct then?
i think probably
instead of assuming, you should consider actually looking at your code and the documentation https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.Raycast.html
ok checked dont work
so based on the documentation and your code, what do you think might be wrong?
propably the fuel collecting function
because it keeps on saying doesnt hit even when i am left clicking while looking at fuel
alright, you've clearly not bothered actually reading anything that has been said so i'm out. good luck.
what yes i have
so then what is wrong with the parameters you've used for the raycast method
because there is, 100%, a problem with the parameters you've passed to Physics.Raycast
oh wait i know whats wrong i forgot to do PlayerCam.transform.position instead of just transform.position
no
ty btw
well it worked
your Ray and your Physics.Raycast call were entirely separate and had nothing to do with each other
oh ok thx for helping me btw
if it is working now, then you've changed more than just the parameters for the Ray constructor because, again, that has nothing at all to do with your Physics.Raycast since you weren't using the Ray anywhere
oh yeah i might have actually look
yeah, you're actually using the ray now which means the parameters for Physics.Raycast are correct. but you can make the ray a local variable again and just construct it on the line before the Raycast like you were doing before
it will work provided you're still using the correct parameters for it
oh ok ty
could someone explain to me like im 5 what serializing is and what its for?
Serializing is basically saving a piece of information so you can use it later.
Say you want to have a timer on screen that counts up. That's cool, but what if the player turns off the game? Then the timer would be 0 when they open it back up! This is where serialization comes in.
You can take your timer number (typically a float/double for seconds) and save that to a file. Can be JSON, just the raw number, or some other format, PlayerPrefs, it doesn't matter. Then when the player loads up the game again, you can take that file, read it, then turn it back into your timer number (this is deserialization). And voila, the timer starts from where it was!
Unity does this for all of its assets as well. You can open any .asset and view their contents, which are typically in the YAML text format.
tldr;
Serialization: data -> savable format
Deserialization: savable format -> data
holy, thanks so much!
actually understood pretty well
just adding some extra context :p
also thanks!
I am trying to raycast a surface to get its slope, but raycast doesnt hit at all
Physics.Raycast(transform.position, Vector3.down, out hit, 1.5f)
On drawing a debug line, it does go through the surface Debug.DrawRay(transform.position, Vector3.down*1.5f, Color.red);
so have a -y in starting position?
Yeah if it starts inside of the collider it wont detect it at all
subtract a bit of the direction vector
in this case, since you're using Vector3.down, you'd subtract, say, Vector3.down * 0.1f
yup that worked. thanks
spent an hour trying to figure what was going wrong lol, and it was this simple thing
even chatgpt didnt suggest that
anyone know why with the new imput manager you need alot of speed to move something? or is it just me
that's not correct . . .
have you looked at the values you're getting?
e.g. just log the number that the input action is giving you
let me try that
probably a setup issue to retrieve the value. what is your default speed, and are you scaling it?
im using rigidbodies and using 10 as default, also using deltatime
rb.AddForce(10 * input * Time.deltaTime);
this would be wrong
deltaTime is the problem . . .
AddForce represents a continuous force
You tell it how hard you're pushing
(at least, it does in the default force mode!)
you don't need to use deltaTime with physics movement. it's already implied in the calculation . . .
This would be more correct if you were doing rb.AddForce(whatever, ForceMode.Impulse) -- in that case, you're telling it how hard you're hitting the object instantaneously
will it still be non fps dependent?
But at that point, just use the normal force mode and don't try to include deltaTime :p
got it
deltaTime is not a magic "fix" for framerate dependency
you don't just use it to make your code correct!
It's used to convert a rate into an amount
they always make it seem like it, its crazy
transform.position += Vector3.right * Time.deltaTime;
This treats Vector3.right as a velocity. I convert it to a distance by multiplying it by deltaTime
rb.velocity = Vector3.right * Time.deltaTime;
This is wrong. A velocity is a velocity.
yes. the physics step runs at a constant rate, not based on a variable rate (deltaTime) like with Update . . .
Multiplying by deltaTime implies we want to turn it into a distance, but that's bogus
this video is a good explainer https://www.youtube.com/watch?v=yGhfUcPjXuE
DeltaTime. This video is all about that mysterious variable that oh so many game developers seem to struggle with. How to use DeltaTime correclty? I got the answers and hope this video will help to deepen your understanding about how to make frame rate independent video games.
0:00 - Intro
0:34 - Creating The Illusion of Motion
1:11 - Simple Li...
well, beyond that, it's just completely wrong to multiply a force by deltaTime and then pass it to AddForce with the default force mode
It's true that FixedUpdate runs at a...fixed rate
but forgetting deltaTime in there also produces errors (by making everything 50 times faster than it's supposed to be, by defualt)
rb.velocity += Vector3.right;
This is extremely wrong in Update and also very wrong in FixedUpdate
In the former, the acceleration is framerate-dependent. In the latter, you're accelerating at 50 m/s^2
oh, for sure. at that point, you're multiplying it twice; hence, why their number had to be huge in order to work . . .
(and if you change the physics timestep, then the behavior changes)
Similar note: Do not multiply mouse input by deltaTime
It's already an absolute amount of change
well now i know that delta time isnt the magic solution i once thought it was
this one happens a lot . . .
and i now have another issue
{
Vector2 movement0 = inputValue.Get<Vector2>();
Vector3 movement = new Vector3(movement0.x, 0, movement0.y);
rb.AddForce(movement * speed);
Debug.Log(inputValue.Get<Vector2>());
}```
i tried making a simple movement script but when i press a key to move the value of the force of the rigid body does not change even when the input is 0
OnMove is called when the input value changes
oh i didnt know that at all
I presume you're using a PlayerInput component here?
yeah
You can leave that in place, but I'd suggest using an InputActionReference for contiuous values. It makes things very simple
[SerializeField] private InputActionReference moveActionRef;
assign the appropriate action in the inspector
and now you can just
moveActionRef.action.ReadValue<Vector2>()
wherever you need the value
the first line is a field to add to your class
i see
so i put this line on the OnMove function?
im a little confused here
No. As I said, OnMove is only called when the value changes.
oh yeah my bad
(by "that" I meant the PlayerInput component)
Just read the value when you need it.
At this point it's identical to how you'd use the old Input Manager
Input.GetAxisRaw("Florp");
florpRef.action.ReadValue<float>();
same premise
alright ok, still a bit bamboozled but ill try that and see where it goes
I mostly use InputActionReference in my game. I find it to be very convenient
Especially if I might need to configure which action is used
i can just throw whatever action I want in there
I directly reference the action that I care about; there are no magic strings
i think im starting to get it
moveActionRef.action.ReadValue<Vector2>() to get the input and just in the update function use it basically as the old input system
Right.
nice
input actions can have many kinds of bindings, and these bindings can have special interactions and processors attached to affect the values
I made a custom processor for sensitivity settings. I don't have to deal with sensitivity at all in my game code
the value that comes out of the action is the correct value, always
I can also figure out exactly what controls are required to trigger an action, so I can display control hints
it's pretty handy
well ill have to get adapted to the new one but i think itll definitely be an upgrade
thanks btw
just tested the code and it worked flawlessly
thanks again
I need an array or list in the inspector that can enforce prefabs of a particular interface, is it possible?
You can't serialize interface types, unfortunately
https://github.com/Thundernerd/Unity3D-SerializableInterface is a close approximation -- it stores an Object, but it gives you a UI to pick objects that implement the desired interface
I don't know about Odin
do you mean creating an abstract class? if so, yes
The prefab doesn't remember the references
When I drag it from hierarchy to project
a prefab cannot reference scene objects . . .
It's other prefabs
are they in the scene?
Oh the little dot only looks in the scene, I thought it searched the entire project
prefabs can reference other prefabs, but only in the project folder . . .
can you get rid of the automatic comments that unity creates after making a new script?
There's a template in the unity program files directory
thanks
On my phone so I can't say where exactly
dont worry ill find it
But if you open it up in notepad, and make sure you have admin privileges on the notepad, you can change it to basically anything
It's quite useful
got it thanks
I wish Unity would make it more obvious that it's something you can actually do
same, i got tired of deleting the comments so i just stopped and my code looked like a mess
I feel like a lot of people never realise they can save themselves the time of deleting the prewritten text 😆
Same in Blender, you can change the startup project to no longer have that cube
i like the cube tho so for me it will stay
if i didn't have the cube, how would i delete something before i start working?
exactly
its the ritual of every new project
its like if unity didnt have the light, camera and the volume
One of the first things I ever did was banish the cube
What you should do is make a default donut in the startup project
Right??
yeahh, honestly the cube has become like a mascot
its synonymous with a new project so thats why i always like having it there, then of course delete it afterwards
i sometimes just do almost everything based off the cube
if i instantiate an object, do all the scripts within it execute the Start() method, or is that during the start of the game
every time you make a clone it will run the script of the clone again
if im not mistaken
I'm making a script for death and respawning, and on the Start method i have this code, so i was wondering if i instantiate the object as another object, would it rerun the script?
okay, thanks
(i just noticed the max stamina twice)
Start runs on every component on every object on the first frame it exists for, right before running Update
ah, thanks
so im having another issue i have this death method, alongside a coroutine, however the coroutine won't start because the player isn't active, is there a way around this?
public void Die()
{
if (deathAnimation != null)
{
deathAnimation.Play();
}
gameObject.SetActive(false);
IsAlive = false;
if (shouldRespawn)
{
StartCoroutine(RespawnAfterDelay());
}
}
private IEnumerator RespawnAfterDelay()
{
yield return new WaitForSecondsRealtime(deadTime);
transform.position = respawnLocation;
gameObject.SetActive(true);
if (respawnAnimation != null)
{
respawnAnimation.Play();
}
IsAlive = true;
}```
Either don't use a coroutine or start it on a different active object.
how could i do it without a coroutine?
Async await would work regardless of whether the object is active. Though, I wouldn't recommend it if you haven't dealt with async until now.
I have, just not in CS 
Ideally, in this scenario you'd have some kind of manager (gamManager?) take care of this kind of logic.
hm, well ill do some research into async await and see what i get
gameManager.EnqueueRessurect(this) or something. And the GameManager would start a coroutine on itself for example.
Or add the player to a queue with a timestamp. And check it in update.
There are many ways to implement it, but the key is that it would be managed outside the player.
At least the waiting is. After the waiting duration is done, the GameManager could call a Ressurect method on the correct player for it to handle the resurrection correctly.
okay i think i made it work with async await, but now im encountering some weird error, i didnt miss a semicolon anywhere, nor a brace
oh nvm
it detects collision with the ground but not the obstacle
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerRB;
public float jumpForce = 10.0f;
public float gravity = 1.0f;
public bool isOnGround = true;
public bool gameOver = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
playerRB = GetComponent<Rigidbody>();
Physics.gravity *= gravity;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
{
playerRB.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isOnGround = false;
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isOnGround = true;
}
else if (collision.gameObject.CompareTag("Obstacle"))
{
gameOver = true;
Debug.Log("Game Over!");
}
}
}
it's better to fix your original code instead of posting duplicate code . . .
make sure the obstacle is setup correctly to trigger a collision . .
oh i just planned to delete that one lol
it is
the is trigger thingy is checked too
and it has the tag
it's a trigger but you're checking it in OnCollisionEnter . . .
that's what the guy did in the Unity tutorial lol
are you sure? can you check again or post it?
here
where does it tell you how to setup the obstacle?
over many steps haha
that part is needed . . .
ohh wait his "is trigger" is not checked
a trigger cannot be detected in a OnCollisionXXX method . . .
how does the on collision detects stuff
with the box colission component?
like when two of those touch?
hey yall, im having problems with locking my cursor, it doesnt seem to work, should it be on the start method or the update method?
pretty much yeah ( in simple terms )
Why is this just flying off now😭
i think you put a rigidbody on it, its not supposed to have one
wait no nvm
probably based on how you setup the object . . .
ill check my file since i have done that same lesson
🙏🏻🙏🏻
In what way?
Like the components it has?
not sure; just like we did before, go back and read over the tutorial. you probably missed smth important . . .
It all worked correctly until I tried detecting collision🥲
what was the problem you were having?
i have my own prototype here so maybe i can help
The player colliding with the fence was not detected
Oh now it is!
But now the fences are flying off lol
Fix one bug get another damn that’s real😭
how is your rigidbody on your obstacle set up?
at least it detected the colission now
what does set up refer to
the components it has?
send a screenshot of the rigidbody component and its properties
this?
i think i saw the issue
try scaling your box collider a bit down on the y axis
most likely that your fence is clipping into the ground while spawning
maybe thats causing the issue
i tried with this but it still flies off🥲
huh thats strange
in the tutorial, where does it setup (create and configure) the obstacle in the editor? go to that section and start from the beginning. make sure you check everything again . . .
keep going through the whole section and check with what you have . . .
hmm this is quite something
you could also try locking the position and rotation of the fence's rigidbody
It happens in the exact same place
then continue and see if they change/fix anything . . .
its best if you retake it and check everything twice
I’ll go over it🥲
its all the same;-;
i even enabled kinematic and it fixed it but now they are falling forward
and i constrainst all 6 boxes and they still fall forward
placing a constraint on the rotation axis that controls its forward and back movement should not allow it to tip over . . .
yeah it should not be able to do that if all the boxes are checked
that is quite strange
Is it related to modifying physics through a script
shouldn't be
but it is quite strange
maybe you could dm me the code from the scripts and compare i could it to mine to see if you have something going on
I am using Unity 2022, and I am trying to use the Init keyword, but I get the error:
"error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported."
Here are the attempts I made to resolve this issue:
- I tried modifying the Api Compatibility Level in Player Settings. There are two options: .NET Standard 2.1 and .NET Framework, but neither resolved the issue.
- I tried upgrading to Unity 6000, but it seems the issue persists.
- I searched for this issue and found that the init keyword is only supported in .NET 5, but I am not sure how to interpret this information.
how are you using it? show your !code . . .
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
public record InstanceInfo
{
public int ID { get; init; }
public IDType Type { get; init; }
}
should i just make the flappy bird game from scrath?
And this seems to have the same error as well.
public record Test(int A);
how else would you make it?
if you're learning it from a video, you are making it from scratch . . .
Should I ask in a different channel?
there are limitations with using record Unity. it's been a while so i'm trying to remember . . .
record has limitations in Unity. init only setters are unsupported (as well as other functions) . . .
And have you declared that type? Because without it there is no support
ok... So my best bet right now is to keep using record, but do the constructor myself?
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit { }
}
OH! i don't seem to be doing this, where do I need to put this code?
Anywhere
ok thanks
I created a new script to write this code and put it inside the project and it seems the problem is solved, thank you very much!
how do i research what i want to do
break it into simple parts
im trying to just for example search how to move a character
and i find nothing on google that i was taught in the Unity courses
it's all so different
there are many ways to move something
2d or 3d? what perspective? etc
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
private Rigidbody playerRB;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
playerRB = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
playerRB.AddForce(Vector3.forward * speed * verticalInput);
playerRB.AddForce(Vector3.right * speed * horizontalInput);
}
}
i wrote this from memory and now im stuck because i forgot the rest
3d third prespective
so i tried searching but i find nothing that will help me complete the code
so whats wrong with it ?
it doesnt work, player doesnt move
you should combine that into 1 call
should work fine, depends on your rigidbody settings too
well if you're just memorizing a specific tutorial then you'd need to refind that specific tutorial
don't do that
understand what each part does, then you can just make everything as you want it
i understand that it takes the horizontal input from the setting and then detects it and converts it into force applied on the rigid body component that is attached to the object
but if i need to search for the syntax how do i do that
how do i search for a specific syntax
what specific syntax?
look up what problem you want to solve
code is just the tool to achieve that
.AddForce(what to put here) for example
that's not syntax, that's just what the method takes
i did, player movememnt, and it gave me a million different things
yeah because thats too vague..
always consult the !docs
hold on ill try and see if i can make it jump just from doccumentation
because i have some problem with that too, i need to get used to that
i never find anything in doccumentation because i initially dont know what the function is called
yeah there is a lot, normally you narrow down the methods in the API thru searching unity discussion/forum, google, stack overflow etc.
then use the docs to clarify how it works n all that
if i want to find an answer in the add force doccumentation for why right now when i press right it goes left what should i look for
thats something you need to start debugging as it might be unintended behavior
hmm I'm going to assume AddForce isn't local spaced
make sure you haven't scalled anything weirdly, and make sure your axes are set up correctly
so you're applying force to World Vector3.right which is always fixed
docs say it's in world coords yeah
doc always got the answers
you want your local right through transform.right or use InverseTransform
yeah transform.right should fix that, it converts local coords to world coords
i multiply by that?
transform.forward too
replace Vector3.right with transform.right
indeed, transform adapts to your local rotation
you're right, they have AddRelativeForce for that . . .
ahh yeah forgot about that func
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
public float jump = 10.0f;
private Rigidbody playerRB;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
playerRB = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
playerRB.AddForce(transform.forward * speed * verticalInput);
playerRB.AddForce(transform.right * speed * horizontalInput);
}
}
could it perhaps be rolling and changing what direction "right" is
also combine that into 1 AddForce call
if it shouldn't be rolling, make sure to constrain rotation on the rb
the first issue i see is the incorrect usage of AddForce in Update . . .
also yeah that should be in FixedUpdate
it was so much easier moving a character in the tutorials
is there a simpler way
i dont remember doing it like this
which tutorial?
which one
there are many ways
it was just straight forward
the unity intro ones use Translate
"simple" is kinda subjective
if you're thinking simple, maybe it was setting velocity?
its not using physics and probably not rolling as was pointed out
if you move the code from Update to FixedUpdate it should work, no problem (unless the rigidbody is setup incorrectly . . .
the ball is indeed rolling and changing local direction
it didnt use velocity
ohh
that makes sense
ill try
must lock the rigidbody rotation
see above ^
he didnt say that in the lab video.. he said "you can just use primitive shapes and then change the model"
shouldve warned for unexpected behaviours haha
send link of tutorial
which one?
idk you said the one that wasn't as complex movement
it probably used translate
ive been stuck on trying to get a basic rigidbody jump working on unity for days
translate just teleports the dam thing
lol
it doesnt care about walls etc.
so it's a bad movement system?
but then you add the box collision no?
depends, if you dont care about physics solid walls n stuff like that
sure, you would have to do it yourself
translate doesnt' care about physics
rigidbodies handle physics
yeah, rigidbody
is there anyone thats willing to look at my work and give feedback?
also Character Controller, its a quasi Physics object
not if you don't tell us what the issue is lol
gotta start with the details
how do i make the ball not roll cuz if im gonna change the sprite later it shouldnt roll anyway
i told you how here @nova kite
rotation ones
the rigidbody jump for a basic capsule on a plane wont work no matter what i try, i know very little so i dont know the best wording lol
define "wont work", and show what you're doing
without code there is not even a clue to whats wrong
start with that, then show components setup
"doesn't work" doesn't give us any info to work with
is it not responding at all? is it giving an error message? is it responding, but not doing the thing you want it to?
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
public float jump = 10.0f;
private Rigidbody playerRB;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
playerRB = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
playerRB.AddForce(transform.forward * speed * verticalInput);
playerRB.AddForce(transform.right * speed * horizontalInput);
}
}
this worked🥲
but this is exactly my problem i want to learn how to solve this on my own otherwise id need someone to spoon feed me on every little thing😫
again should stillcombine that into 1 call
how would i learn what you guys just taught me from documentation
i tried and it broke haha
you probably wouldn't
you would learn from the manual or learn pathways instead
what is pathways
documentation is a reference to supplement primary learning materials
the stuff on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
oh but they didnt even use that there
depends on the pathway
they used the transform thigny
Ok, so i asked chatgpt for help as i do use it for reference (im not a coder lol). I followed the instructions, included the needed code, the ground check in unity, and the rigidbody component in the inspector for the capsule. According to chatgpt this should give me everything i need to "jump" up and down with my capsule, but it simply does nothing when i input space. There's no error message, it's literally just no response. I'll pull up my code
void FixedUpdate(){
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
Vector3 direction = transform.forward * verticalInput +
transform.right * horizontalInput;
playerRB.AddForce(direction * speed);
}```
could move speed outside
Vector3 direction = transform.forward * verticalInput + transform.right * horizontalInput;
direction.Normalize();
playerRB.AddForce(direction * speed);
it's a 3d structure
actually nvm ill be back later maybe
because thats what AddForce expects remember?
Vector3 is just a list of 3 floats
those 3 floats could represent anything; here, they represent cartesian coordinates
var replaces the type in a local variable declaration, for when the type is obvious from the initialization, so you don't have to repeat yourself (whether you prefer it or not is subjective)
ohh this:?
Declaration
public void AddForce(float x, float y, float z, ForceMode mode = ForceMode.Force);
the first one is a vector3
thats a different signature
we're using the first signature here
but yes you can also use each float here, not all of them have such varied signatures
cc.Move() for example has no such signature
then what tells you on the documentation that it expects a vector3 haha
it says force
Force vector in world coordinates.
Force is applied continuously along the direction of the force vector. Specifying the ForceMode mode allows the type of force to be changed to an Acceleration, Impulse or Velocity Change.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody.AddForce.html
Declaration
public void AddForce(Vector3 force, ForceMode mode = ForceMode.Force);
yes so like the first is vector3
yes that would be that signature
= in signature method means it has a default value, here is to Force
and then if you didnt know what that is youd read about that?
forceMode for example i dont know what that is so how do i know what it expects
click the links
they are underlined
the second parameter, ForceMode mode, specifies what kind of force to apply, basically what quantity/dimension/unit force is in
the = sets a default, to Force, basically in newtons (though not exactly newtons since unity doesn't use meters/kilograms)
ohh! and it takes you to that function's page
ohh
hahah
what is that word
lol
lol i shouldve made it wide af
XDD
which word?
enumeration
"enumeration" is like a list of options
thats basically a standard C# type
oh enums!
yes
nvm i never saw the full word lmao
see the "enumerate" -> "numerate" -> "make into numbers"
more accurately it's just kinda listing them
just fancy word for numbers with labels
wait on the ForceMode page there is a huge block of code, how do you research that code to see what it expects
you just read all of it??
wdym "research that code"
its just an example script, there is nothing to research
it has comments explaining what each part does
in order to arrive to this conclusion
how do i stop from sticking to walls if im in the air?
reduce friction perhaps
ouu so the enum stores the 4 modes
make a material with 0 friction?
yeah
though if you do want it to have friction in some cases, you'd probably have to do more work
and what can i do if i need to stand on that thing ?
wdym 4 modes?
i guessed so
(the 4 force modes)
Impulse, Acceleration, Force, VelocityChange
Ohhh forcemode
oh 5 and start
friction wouldn't affect standing wdym
yea that enum just has "human readable labels" the computer just sees a number
you can also assign different values but thats topic for another time lol
i meant moving on top of it sorry
would it be affected?
friction wouldn't affect moving, since you aren't literally pushing off of the ground in the game (for most implementations)
wait so how do i know what it expects like for the force mode
got it
i read the description
it just expects ForceMode, which one you use depends on what kind of forcemode you want
the method just cares about the type in the signature
the value is up to you
but it could make the surface slippery when coming to a stop. you could set linear drag to compensate but you'd have to keep that in mind for other surfaces
if it's like, a rock that you want to have friction on one side (the top) and no friction on another (the side), then maybe you could set up separate colliders for that?
and how do i know if it's a float or an int
@wispy coral
like obviously its a float but im asking like in general
read the types in the declarations
whats a float?
it says rigidbody and vector3
probably will set up different colliders or just put a plane on top and call it a day
i know what float is, I'm asking you
oh lol
then it neither expects an int nor a float, it expects those 2 types
you said "float vs int"
like obviously its a float
so i asked "what is the float"
however, vector3 holds floats inside
(this is not quite the same as a float btw)
im so confused hahahah
float double decimal, we are not the same
XD
it can hold more numbers or something no?
it's a bit technical, yeah we can get to that later
it's along those lines, but a bit more nuanced
do you know how int and float differ semantically?
on the Rigidbody.AddForce page it says that it needs a vector3 then a ForceMode
i got that much
but then in the example code it doesnt even include the public void AddForce()
or more precisely, how integral types differ from floating-point types
right, it shouldn't
wdym
m_Rigidbody.AddForce(transform.up * m_Thrust);
public void AddForce(...) is the creation of the method
the example shows how to use the method
its like the declaring of the method
so i need to create the method too or does it come with the include unity
how is this method structured
if it had that creation, that'd be the source code of the method, not an example usage
well, if it didn't come with unity, there wouldn't be much point to documenting it as part of unity
AddForce is a method that comes from the Rigidbody class, which is a component here
i meant like do i need to put that line in th ecode
no, unity does
i see so that's just showing me what it expects
you just need to "call" the method, you dont declare it
like what values i need to transfer to that method
the method is already setup for you. You just "feed it" values
playerRB.AddForce(transform.right * speed * horizontalInput); how come it's different here then
there is no comma
so where is the ForceMode
because its using default forcemode
it's defaulted
i told you what = meant in signature
yes but i dont have it
its giving a default value so you can omit it
so how does it know
unity has it
it has been given it when it was declared
you don't have to
same idea, different thing
its still using ForceMode, but the default one
when you declare a method you can have it default values in params so you dont ever have to pass a value
ohh
so basically in the example code they show me the items i need to make it work
i need a rigidbody reference
and to connect it to the component of the game object that this script is attached to
yeah you need a specific rigidbody to access/call the method on
and then i can do stuff with it
you can think of defaults as hidden overloads
void Method(int a, int b = 0) { /* stuff */ }
// is like
void Method(int a) { Method(a, 0); }
void Method(int a, int b) { /* stuff */ }
yes thats exactly what i had in mind haha
like different options depending on what the user passes
so by writing ForceMode mode i crete an object or however that's called and then i assign it a certain mode's value
and that gets passed to the rigidbody class who has a reference to that ForceMode enum and then it applies the propoer physics
by writing ForceMode type you're overriding the default value, nothing more
i meant like the "mode" that coems after ForceMode
AddForce(float x, float y, float z, ForceMode mode = ForceMode.Force);
that's like an object of that enum
thats how enums work, you preceede it with the enum type
public enum Colors{
Red, Blue
}
private Color col;
void Foo(){
col = Colors.Red;
}```
like that stores what mode i want to use
i see okay this all makes much more sense now
thank you guys!!
Vector3 direction = transform.forward * speed * verticalInput + transform.right * speed * horizontalInput;
playerRB.AddForce(direction);
and for this how does it work even tho you add these two up? wont the numbers just get messed up
yess that's what i imagined too
i like when i think of something and it's actually the answer that's when it clicks lol
hey guys! i dont really know why my character hasnt been being triggered, but i got a player
using UnityEngine;
using System.Collections;
public class Collision : MonoBehaviour
{
private void onTriggerEnter(Collider other) {
if (gameObject.tag == "Player") {
print("Entered hitbox");
}
}
}
and a monster, i added this code to the monster's empty gameobject trigger and gave it a box collider, i checked the isTrigger checkbox and made a tag for the player called Player however this still doesnt work, can anyone tell me why?
its doing the same as what you did , its just adding the two directions instead of calling them seperate
but how does it not add the resulted numbers of them
or that wouldnt matter cuz it would be like going sideways?
try other.CompareTag("Player") maybe it will help instead of gameObject.tag
it checks the tag of the other thing, that being the player and does the action
imagine you did Vector3.forward(0,0,1) + Vector3.right (1,0,0)
what do you get ? (1,0,1)
can you even add these hahah
yes
nope! it didnt work
then i would assume so yes
should i add anything into the player?
dang i tried
i would assume it adds the x y and z seperately
did you read what I sent?
look carefully
i was already reading that before!
wait, am i not catching something super obvious?
how do you not see whats wrong then lol
yes
C# is case sensitive
fuck im sorry guys LMFAO, i have been looking at this for like the past HOUR
it just comes down how they do math , you can't multiply 2 vectors for example
glad you found a solution
Also you should use CompareTag instead of comparing tags with equality
using UnityEngine;
public class Example : MonoBehaviour
{
private float speed = 2f;
//Moves this GameObject 2 units a second in the forward direction
void Update()
{
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
//Upon collision with another GameObject, this GameObject will reverse direction
private void OnTriggerEnter(Collider other)
{
speed = speed * -1;
}
}
why is that?
adding is pretty straight forward math (x1+x2,y1+y2,z1+z2)
Because it warns you if you get the tag wrong and it also doesn't allocate an extra string
i see so it would move these two simultaneously if two buttons are pressed that's clever
i see! could you explain to me how the Get.Component works? is it a way to reference another gameObjects inside unity?
Yes
this is from the OnTriggerEnter documentation
it has GameObject written there but it's actually gameObject
so how do you know which to use
Because one is a type name and one is a property of Component
They make sense in different contexts
yea but if you didnt have context and relied on the documentation?
because that's what im trying to learn haha
how to rely on documentation
start clicking stuff 😛
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Component.html
The documentation is using things in different contexts, I don't see where a capitalises GameObject is even referenced in what you quoted outside of a comment
click it, GameObject it explains everything
its telling its being applied to that Gameobject this script is on
and that's to get components of game objects
GameObjects are just containers of Components
in the example code
when you put a script on a gameobject its a component
Unity is traditionally component based
of how to use the ontriggerenter
also, just a final question, i used Destroy(other.GameObject) so the code looks like this
{
private void OnTriggerEnter(Collider other) {
if (other.CompareTag("Player")) {
Destroy(other.gameObject);
}
}
}
but i get this error SPAMMED in my console, am I deleting only the camera?
so that would be like GameObject.component
thats when you use capital G
I don't see where a capitalises GameObject is even referenced in what you quoted outside of a comment
ohhh
so how do you know how to write the code that would be on a trigger detector object
no GameObject is the type you reference if you want to use its methods or holding reference to an object
if that example doesnt have it
GameObject.component doesnt exist
click GameObject, you will see all the properties and methods listed
You're not showing the stack trace, and I doubt this code relates to this error
Because it's not relevant in this example. You can find the properties of a GameObject class in the corresponding class page in the docs.
i meant get component haha
You follow one of the thousands of relevant tutorials
you got it right! this error is coming from my navigationscript where its trying to access a character that doesnt exist after its destroyed
I just look at the docs its pretty straight forward how it works
access the method for rotation
put Quaternion.identity
then i set it to 0?
or whatever you want to reset to
is there a tutorial that explains how to understand documentation lol
identity means no rotation, you can also use whatever Quaternion value you want just pass it through a euler angle (vector3)
You don't need such a tutorial. It's intuitively understandable. You just need to know some C# basics.
Having traditional C# basics will help you better read the Docs / APIs
oh didnt know that, my ide was kinda ambiguous about it
so, question, should i use GetComponent to get a variable in another code? i was thinking of making a isAlive boolean variable
or is there a better way?
how different is it from C++ because so far i havent seen much difference
its the same family language so they are similiar, but c++ lets u get real granular and you have to manage your own allocations / memory
no garbage collector like c#
It's quite different. You should read the C# manual. I think they even have a section for programmers coming from C++.
i hate pointers lol
c# ur not typically dealing with pointers directly
luckily
ohh
thatll be helpful
if you know c++ , c# will be easier lol
i know some we are studying it in college
Though, I feel like there's not much knowledge you'd be able to transfer from C++, seeing how you "hate pointers"😅
less to deal with, I mean header files? ughhh
i fucking hate header files
maintaining 2 files is annoying
hahaha it's so confusing and every time i think i get it i dont
yess and so confusing im not about to do that at all
agree lol
welcome to the eazy life then
Putting all the code in the header. 
Now you only have to maintain one file.
Pointers are an indispensable part of C++. Saying you hate them is like saying you hate table legs in tables.
hey quick question, anyone ever experienced button taps "randomly" not detected on android build? where should i look to find the reason?
facts. if you hate like pointers, basically, you don't like C++ . . .
start by showing how you capture input in code
i like how the input and output work lol
I had an entire sem of C.
My teacher literally didn't teach anything.
oh god
Just gave us projects and went go work on it urself.
we are forced to take assembly too😭
i just use C/C++ for embedded and connecting to unity via interop sometimes
Can you also use pointers in rust?
shootButton.onClick.AddListener(OnShootButtonPressed)
is there a way to unfreeze a single rigidbody constraint on command?
okay so its a UI button, could be something covering your raycast press area
yes
just unfreeze and assign the specifc one you want
alright thanks
good quuestion, though, i wouldn't know. haven't used Rust. i know a few other people here have . . .
yes: it's a bitmask, you do it using bitwise operators . . .
i have no clue what that is and it sounds scary
i just unfroze all and froze the ones i didnt need
Bitmask.
000
You basically have some flags.
And you have some operators to combine them.
yep
i guess ill have to investigate about em
thats convenient actually
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
playerRB.AddForce(Vector3.up * jump);
}
}
why does it not jump😫
because in one frame you aint going nowhere with addforce force mode
because you're using the default force mode . . .
^ use Impulse for one frame bursts