#💻┃code-beginner
1 messages · Page 275 of 1
When any vector is divided by its own magnitude, the result is a vector with a magnitude of 1, which is known as a normalized vector. If a normalized vector is multiplied by a scalar then the magnitude of the result will be equal to that scalar value. This is useful when the direction of a force is constant but the strength is controllable (eg, the force from a car’s wheel always pushes forwards but the power is controlled by the driver).
When normalized, a vector keeps the same direction but its length is 1.0.
https://docs.unity3d.com/ScriptReference/Vector3-normalized.html
I was using
if (Input.GetKey(KeyCode.W))
{
rb.velocity += direction.normalized * acceleration * Time.deltaTime;
}
and my space ship would just go flying
you keep adding onto the current vel
i switched it to
should prob be rb.velocity = direction.normalized * acceleration
ok dont want to do that
let me give that a try
cause im now using
if (Input.GetKey(KeyCode.W))
{
// Convert transform.up to Vector2
rb.velocity += rb.velocity += transform.up * acceleration * Time.deltaTime;
but i have a ambiguous error
that comment is old
Don't use Time.deltaTime with velocity. (It is already per second)
Do you have using system.Numerics btw?
ah yeah prob this
not even sure for new and just trying to learn hands on
Do you have the words "using system.Numerics" at the top of your file?
no
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
can i post the whole code it isnt long
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also copy the actual error.
It wasn't what I was thinking
{
public float acceleration = 5f;
public float deceleration = 2f;
public float maxSpeed = 10f;
private void Update()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
transform.up = direction;
Rigidbody2D rb = GetComponent<Rigidbody2D>(); // Cache the Rigidbody2D component
// Accelerate when pressing W
if (Input.GetKey(KeyCode.W))
{
// Convert transform.up to Vector2
rb.velocity += rb.velocity += transform.up * acceleration * Time.deltaTime;
}
// Decelerate when pressing D
if (Input.GetKey(KeyCode.S))
{
rb.velocity -= rb.velocity.normalized * deceleration * Time.deltaTime;
}
// Limit the speed of the spaceship
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxSpeed);
}
}
i think the error is them doing vector2D + Vector3D
that didnt do what i ment
!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.
sorry!
the rigidbody2D velocity is vector2, transform.up is Vector3
I thought i copied the link
so its ambiguous + operation
Severity Code Description Project File Line Suppression State
Error CS0034 Operator '+=' is ambiguous on operands of type 'Vector2' and 'Vector3' Assembly-CSharp C:\Users\nick\Shambles Ship\Assets\Scripts\Followmouse.cs 32 Active
Oh no worries. I was jumping back and forth and honestly forgot I did that here earlier even though it was like a second ago lmfao
got it is there a way to fix it without redoing most of it
or did I just do this all wrong?
yes rb.velocity += rb.velocity += transform.up * acceleration * Time.deltaTime; this is hella wrong
lol yup i could tell by the way my player moved
like i said if you don't want it to keep increasing speed don't keep adding the current vel/speed to itself, twice..
for example rb.velocity = transform.up * acceleration
or rb.velocity = direction * acceleration
rb.velocity = transform.up * acceleration worked
error gona just some re-order errors
btw ideally you want to keep inputs in update and move rigidbody on FixedUpdate as well
what do you mean? (im super new to this and if you don't feel like explaining I understand)
rb.velocity =
should go inside FixedUpdate()
but keep inputs / mouse direction in Update
use floats / vector 2 to store the inputs from Update in variable to use in FixedUpdate
also doing this inside Update is kind of bad on performance
Rigidbody2D rb = GetComponent<Rigidbody2D>(); // Cache the Rigidbody2D component
put it out side update
at very least it should be once in Awake () where rb stored in the class not locally too
and I broke everything.... I think I have some reading to do
send link of current code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
im embarresed to even show it. It's a combination of message boards, tutorials, and chat gpt
don't use gpt at all, its only hurting
why is FixedUpdate nested inside Update..oh no..
yeah im realizing that. Did alot better without it
this is def an compile errror
private Rigidbody2D rb = GetComponent<Rigidbody2D>();
is your IDE not configured ?
should be underlined red
said the function should be in awake since it only runs once
but rigidbody variable should be stored in the class yes, outside of a method
you cannot perfom a method on fields when you declare them
Hi there sorry if I'm cutting in, I'm looking to improve my Debugging techniques and safe to say its already going off to a flying start 🙃
for some reason when i draw my lines they are aligning to (1, 0, 1) in world space instead of being local to my game object, however Debug. Log shows that localNodePos is converting the the coords. i tried researching to find out why this is happening but couldn't find anything
void Update()
{
for (int i = 0; i < nodePos.Length; i++) {
Vector3 localNodePos = transform.InverseTransformPoint(nodePos[i]);
Debug.DrawLine(transform.position, localNodePos, Color.red, 0.0f, false);
Debug.Log(localNodePos);
}
}
ok i made it even worst
InverseTransformPoint converts from world to local. the params for drawline are both supposed to be world points
everything is now red
you are randomly changing things without having any fundamentals
it will break things
perhaps take basic course https://learn.unity.com/project/beginner-gameplay-scripting
ty
oh, so essentially just:
Debug.DrawLine(transform.position, transform.position + localWheelPos, Color.red, 0.0f, false);
im not sure where wheel came from, but from the previous code you could likely just do
Debug.DrawLine(transform.position, nodePos[i]).
If you have the direction you can just use https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html
anyone thinking?
previous variable name, i was playing with physics before and pressed Ctrl + z 1 too many times. 😝
the working solution i came to was this:
Debug.DrawLine(transform.position,transform.position + nodePos[i], Color.red, 0.0f, false);
make another bool ?
if nodePos[i] is a world position, then it doesnt really make sense to add. if its a local position then you can just use drawRay but yea itd be the same thing
Ahhh I see now, I thought the direction vector inside the parameter would need to be normalized & the distance would need to be manually calculated. thanks for your help
for DrawRay
How might applying a velocity to a 2D rigid body randomly break? I’m not sure what cause it, but I’m currently setting an objects velocity with rb.velocity. And when I inspect the rigid body component after the velocity has been applied it shows that it has the expected velocity, yet it doesn’t move anywhere. There’s nothing obvious that it could be colliding with either, so I’m stumped to be honest, anyone know why this may be?
show inspector for the object
not cropped. the entire thing
@rich adder i fixed it
yeah that's not the problem, i can see it.
I don’t get how an object can have a velocity yet be stationary regardless, that makes zero sense
what would i search if I wanted the feature that supermarket sim has where it places an object on the slot you click?
basically a box on a rack
well if Simulated is not ticked then I expect its not gonna go anywhere 😛
Oh my how did I miss that I’m stupid, thanks. I was so confused because it suddenly stopped working, I guess I must’ve accidentally unchecked it
oh? another bool?
either that or start doing state machine
maybe splitting your code up would help disabling certain features
uhhhh... my heard is literally spinning around by this
welcome to gamedev 😈
i loveee state machinessss
I thought it was something like freeze position and then unfreeze position type of thing?
if(chargingJump) return;
//rigidbodyMovement
hey when you are loading another scene do you have to deload the one you are currently in? when i try to load another scene it just puts it in the hierarchy, here is my code: https://hatebin.com/zywhfrojad
thats because you're using additive
do you know what that is ?
no, i'm not fully familiar
yes the api docs is pretty good lol
heh i actually checked that at first, i just missed that part
if you omit the second parameter for loading mode, it defaults to Single
i am so confused as to why I'm getting this error :/
how are you declaring it in your script?
public class PlayerContol : MonoBehaviour
{
public Rigidbody rb;
public Transform[] nodePos = new Transform[4];
public LayerMask mask;
public float springRestPos = 1f;
public float springForce = 10f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
for (int i = 0; i < nodePos.Length; i++) {
Vector3 localNodePos = nodePos[i].position;
RaycastHit hit;
if (Physics.Raycast(localNodePos, Vector3.down, out hit, Mathf.Infinity, ~mask)) {
float offset = springRestPos - hit.distance;
Debug.Log("Position of node " + i + ": " + nodePos[i].position);
if (offset > 0) {
Vector3 force = Vector3.up * offset * springForce;
rb.AddForceAtPosition(force, localNodePos);
Debug.DrawRay(hit.point, Vector3.up * offset);
Debug.Log("pass");
}
}
//Debug.DrawRay(transform.position, localNodePos, Color.red, 0.0f, false);
}
Debug.Log(nodePos.Length);
}
}
are these being assigned to the prefab?
if you have one
its not set up as a prefab atm, its just a game object with 4 empties inside it
Hi, I've got a design issue: my player wants to interact with world objects some of which have purely self contained logic (like a door that opens and closes) where others have a combination of self contained logic but also interact back with the player (like a piece of equipment that would need to be picked up or anything else that otherwise affects player state). My solution thus far is to have an interactable interface with a query method that passes a player reference to the I_Interactable object. This I_Interactable object then has the option of calling public methods on the player using the passed reference. The only public parts of the player are the methods that interactable objects can call; see the example where a player interacts with a piece of equipment which then calls the players RequestEquipmentSlot. Is this an acceptable way of doing this? To scale for other interactable objects with callbacks I just need to add more methods to player, is this acceptable? I feel this is a common concern that arises so are there standardised ways of doing this? Is there perhaps a way of specifying in the InteractQuery of I_Interactable that should it call any functions, it can only call functions of the signature (this, InputAction.CallbackContext)?
are you sure you dont have a copy of this script
search hierarchy t:scriptname
You have at least one Player Control without having this variable assigned. The one in your screenshot does have it assigned, so it's not this object
the only thing i can think of is that these are being destroyed during play
i just deleted the cube and reapplied the script and the error was gone
and now im thinking i probably applied it twice to the same object
.... i did 🫠
on that note think its time for bed 🫡 thanks all for the assistance
I'm currently using a lot of UI buttons with the On Click method in the editor linked to my script, will that work on steam deck, mobile, ...?
Is the click converted to a touch screen tap?
Yes. UI buttons(or more specifically the event system) work on all platforms.
I am trying to make a character move around the screen but with no gravity so without a rigidbody. Could someone pls give an example of how I could get started in doing this? all the tutorials I've seen use myRigidBody.something * something or whatever
like, if i want my character to move to the left, i know i would have to start with something like this, but where do I go from there?
you can just disable the gravity
oh fr
that
ok
yeah i guess i could do that
3D uncheck it, 2D gravity scale 0
👍 ty
Screen.SetResolution(resolution.width, resolution.height, false);
Debug.Log($"ِCurrent resolution height {Screen.currentResolution.height} and width {Screen.currentResolution.width}");```
Guys i have problem with changing my game resultion the first debug showing the desird resolution but after doing screen.SetResulution nothing changed could it be relate to display mode or somthing can somone help me
Where are you testing it? Hopefully not in the editor
Im trying to drag my GameUI canvas into this Script variable, But it either says "type mismatch" or gives me the crossed out circle:
Can't drag scene objects into prefabs
Ohh gotcha, appreciate it!
I am stuck on moving UI element on x axis slightly back and forth:
// Update
Vector2 pos = new Vector2(transform.position.x + xOffset, transform.localPosition.y);
transform.localPosition = pos;
Trying different things, but localPosition seems to work best, but only if I create Vector2 out of .position.x, if I use localPosition.x then UI flies off somewhere.
But even with the above, its still flying off just slower 😐
Moving it in the inspector requires me to move it by 100px on x axis to move a bit, but with the code above it moves it by 100px per second, even tho xOffset is between -3 and 3(so the idea is to move it back and forth 3px)
What do I do to move UI element properly?
I might need to use RectTransform.anchoredPosition
rectTransform.localPosition += (Vector3)pos;
rectTransform.anchoredPosition += pos;
This works 😐
In this video the stone at the start is mass placed through terrain.The script isnt running icant touch it for somer reason.Then i place the same stone through inspector then the code runs i can touch it .the code doesnt run on mass placed objects can someone help
do i need to create a script to spawn the prefabs?
im here i need to do so that on the spawncoords if the texture is GroundTexture execute a code.How do i do so
i have one [SerializeField] private Field field and a static function that uses this field but since i cannot make the field static what shold i do
static function means the function is associated with the type, not any instance. your field is associated purely with an instance. Either pass an instance to the function, or redesign what you are doing
it helps if you state your actual use case, so people can suggest better
so i cannot make serialized field static right
im just trying to know the general step taken for this phase
it wouldnt really make sense to do. as for your next step, i cant really say without knowing the use case. the solution is either make the value static, dont make the function static, or pass an instance to the static function.
all of them depend on what you're doing. static functions are generally supposed to have no relation to an instance of the script
Okay
[SerializeField] private static List<Item> validItemList;
public static bool IsValidItem(Item validItem)
{
return validItemList.Contains(validItem);
}
any workround keeping IsValidItem static?
Item is a scriptable object btw
You really should describe what your actual goal is but this is what singletons are usually used for
unfortunatly this class is not going to have one instance
If there are multiple instances then how would you know which validItemList to use?
yup thats gonna be constant for all
Then why can't you make it static?
make what static? the serialized field?
sounds to me like you need to implement the ISerializationCallbackReceiver interface
Yes, the thing that you asked about
that way you can have the static varaible and yet still serialize it
Hi, I have been working in a camera following script to make the camera go at the same speed as the player (the speed increases with time) but, if the player gets stuck, the camera still has to move. Also, the camera has to follow the y cord of the player so if the player jumps, the camera also does.
The problem I have is that when both things are in the same script, the camera follows the player, but the player does a blinking (I can do a video if needed). And if I do it in a different script, when reading the speed from the player movement script, throws "NullReferenceException 'Object reference not set to an instance of an object'"
To move the camera I use this (image)
if i make it static NullReferenceException: Object reference not set to an instance of an object
well you obviously have to create the list and fill it with whatever you want
A fast and easy (maybe not so pretty) solution would be just
private void Awake()
{
if (static_isInitialized)
{
return;
}
static_isInitialized = true;
static_validItemList = instance_validItemList;
}```
Realistically your solution is probably needing to redesign this. Like why does every instance of the script need to compare if its within the same list?
There are many solutions, you said there are instances of this script so you could also just make both non static then call it a day
i don't understand how i can use that to fix this
yeah seems to work
so i should make another script with public static list<Item> and get that reference with Instance right?
in the serialize interface copy the static list to a serializable non static list. In the deserialize if the static list is empty copy the non static list to the static list
Null errors are always the same, something is null and you are trying to use it. Also you should just use cinemachine
When I declare the variable i do it with a value, then how can it be null?
Making another script wouldnt really help here, it's just moving the problem elsewhere. What other people said will work, but I meant this shouldnt be a thing in the first place. You still havent said what the use case truly is so I cant really say more
Show where you assign player movement
If you do initialize it at declaration, then it shouldn't be null unless you're resetting it after that. But do you actually?
These variables can't even be null. They're value types
You must be misunderstanding something
The image you sent here has 3 variables that could be null.. cameraRB, player, and PlayerMovement
The variable I noted is clearly null
Regardless, we shouldn't have to go off images. Stack traces should be provided, same with line numbers
Line 20, when trying to debug the var PlayerMovement.updatedSpeed
👆
sorry what does that mean?
Neither of those things are PlayerMovement
Your Player is assigned, but what about PlayerMovement. It won't magically know which instance to use to access these fields
I should do [SerializeField] public readonly playerMovement PlayerMovement; then?
Yes, but without readonly.
and make it private if you're using SerializeField
how do I specify that the player isnt touching a wall? the bool that lets you walljump is staying turned on when i leave the wall, idk how to make it turn off
I did that, but i cant assign the script to the serialize field
You don't assign the script, you assign an instance with that component
bool = false;
You're welcome
oh yeah, mb
yeah that does nothing, it doesnt turn off by itself i need to force it to turn off by making it so it cant be turned on if the player isnt touching a wall
Now works but still does this blinking
Wat? You're saying that = false doesn't set it to false? That's impossible
Maybe the wall check is still happening and returning true, setting the bool back to true straight after being set false
it gets set to true when the player isnt grounded and is touching a wall, and it gets set to false when the player jumps off a wall, but that's not working and theres also no way to set it to false if the player doesnt jump and just leaves the wall
yeah i think so
so, go through your code and find out where that is happening.. and tweak the wallcheck
idk what I could change, it's just "if contact.normal.y < 0.1f, walljump = true"
If you need better help, you should share your !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.
Did you consider using OnCollisionExit?
where would I use that?
In your code. It would be called when you stop colliding with the wall(or anything else)
i wouldnt know how to specify im leaving the wall
I just told you how.🤔
I'm confused
yeah it works
thanks
is there no way to just write a line of code that says "else if there's no contact.normal.y, bool = false"
can someone help me, i go to build my game it loads and after it loads i go to my folder and nothing is there
and right after it builds my pc freezes for a second
all the forums ive seen are abt 11 yrs old so idk what to do
the use case is that this file uses validItemList for some public function and is attached to multiple game objects, then i wanted to make a static function which i can use this file to check for validItemList that can be used in other scripts
If I have this class labelled as abstract, with a virtual method in it, with a class that derives from this one that overrides said virtual method, will calling SaveInventory in this case in the abstract class just do what the method in that abstract class does or the method that is overriden? ```cs
public abstract class InventorySO<T, I> : ScriptableObject where T : InventoryItem, new() where I : class
{
public void Start(){
SaveInventory()
}
public virtual void SaveInventory()
{
}
}```
public class ProcessedInventorySO : InventorySO<InventoryPlainItem, ProcessedItemSO>, ISerializationCallbackReceiver
{
public override void SaveInventory()
{
string json = JsonUtility.ToJson(new ProcessedInventorySaveClass(inventoryContainer), true);
if (inventoryContainer.Count != 0)
{
File.WriteAllText(Application.persistentDataPath + "/ProcessedInventory.json", json);
}
}
}```
Hey, now works perfect, thanks for sending me this link <3
Virtual methods have nothing to do with abstract classes, they can be anywhere (well, besides structs and static classes). As to which version will be called, it will be the overridden one. The base version will be only called if you call it directly in the overridden version via base.MethodName(params)
But if you want some base functionality in an abstract class, then you can always just do this:
public abstract class AbstractBase
{
public void GeneralMethod()
{
// Base stuff
// ...
CustomImplementation();
}
protected abstract void CustomImplementation();
}```
And not care about calling any base method
Oh do I not need to specify what each collision is?
yeah that worked, thanks, I didn't know it worked like that
is there a way to make it so the player falls slower while a certain bool is active? I keep trying to look it up and the only results are how to change the game's physics completely which isnt what I want
yes
Ive done this
Lemme see how I did it one seond
okie cool
//gravity
rb.AddForce(-Vector3.up * gravityForce);
mine is just like tbhis
So set you normal rigidbody gravity to the "slow" one and then add an additional gravity force when not slow
Guys im having a problem with a countdown timer
if (countinTimer > 0)
{
Time.timeScale = 0f;
countinTimer = countinTimer -= Time.fixedUnscaledDeltaTime;
}
else
{
Time.timeScale = 1f;
timerTime = timerTime += Time.deltaTime;
}
I want it to countdown for 3 seconds, then start counting up
Its a speedrunning game
the counting up is working fine, but the countdown jumps from 3s to -1.5 on the first frame that the game is played
creating a main menu for my first project (following a tutorial), trying to get the start game button to load the main scene where the gameplay happens: i've created a script with a function that starts the gameplay scene, added an on click thingy to the button in the inspector and attached the aforementioned script, but when i go to assign the function of it, it doesn't show up, any help?
@slender nymph Is this the place I'd ask for support?
is your issue code related? if so, read the channel name and description and decide for yourself
regular douche then aint ya, it might be, or it might be something wrong with something else like layers or something. I don't know, thats the point
I don't know enough about coding to know if thats the issue, or if its something else I've gotten wrong
well you've not provided any useful details about your issue so i have no idea what it is. but you've also just guaranteed that i won't help so good luck
Sounds like I don't want your help with your attitude lmao
figured it out with this, appreciate it :)
If only they would actually share the issue instead of making a scene
Hard task for some
Trying to set a breakpoint in this method but it says it won't be hit. Is there any particular reason why? ```cs
public class ProcessedItemDatabase : ScriptableObject
{
public ProcessedItemSO[] items;
public Dictionary<ProcessedItemSO, int> ItemToId = new Dictionary<ProcessedItemSO, int>();
public Dictionary<int, ProcessedItemSO> IdToItem = new Dictionary<int, ProcessedItemSO>();
public void CreateDatabaseDictionaries()
{
ItemToId = new Dictionary<ProcessedItemSO, int>();
IdToItem = new Dictionary<int, ProcessedItemSO>();
for (int i = 0; i < items.Length; i++)
{
ItemToId.Add(items[i], i);
IdToItem.Add(i, items[i]);
}
}
}
Do other breakpoints work?
Ah, actually it unassigned the scriptable object in the editor, that's probably why
the fact that it does that whenever I change the script is a bit annoying I will say
It should not unassign it as far as I know
Your script has an id and that's the thing Unity assigns, so for some reason it has to unassign it
Perhaps you have code that does this?
Well there have been many occassions where changing a scriptable object has just unnasigned every instance of that in the inspector
Hey, I have used the following method to play the crash sound when the bullet prefab collides with enemy prefab object that's instantiated and the volume of the sound is way too low.... I believe, since these two objects are being instantiated and not in the Scene view like a player object, the method used has reduced the volume of the crash sound, and I can barely hear on speaker, below is the line of code I used, can someone please help me do better...
AudioSource.PlayClipAtPoint(crashSound, other.transform.position);
since these two objects are being instantiated and not in the Scene view like a player object
instantiating an object puts it into the scene.
but perhaps you should pass in a higher volume as the third parameter if the default of1is too low
ah wait scratch that last bit, 1 is the highest it can be
so perhaps the issue is that you want to use an actual existing AudioSource component in the scene so you can adjust its 3d sound settings rather than just using the default
I just want the sound to be loud and clear as other sound that I have attached to Player object which plays with very good volume, but for the enemy and bullet prefab, I had to use the above mentioned method since they are not in the Scene view like player and they are just being instantiated and I believe because of this reason, I can use the following method for player since it exist in the Scene view: AudioSource.PlayOneShot(crashSound, 1f);
But when I try to use the same method under Bullet Script, it isn't working since the bullet and enemy objects are instantiated only after the game starts and not in game scene...
enemy objects are instantiated only after the game starts and not in game scene
again, instantiating the objects puts them in the scene
you do not need to use the static PlayClipAtPoint method if you just get some reference to an existing AudioSource
Does anyone know how I'd make the sprite flip based on if it's touching a wall to the left or right of the camera? My wallslide sprite is facing to the right so it only looks right if the wall I'm touching is to the right (or front) of the camera, I need it to flip to the other side if I'm touching a wall to the left
get the normal of the surface your object is touching, then you can use Vector3.Dot to determine how close to the direction your object is facing that normal is, if it is within some threshold of the direction your object faces then you don't need to flip, otherwise flip the sprite
how do I get the normal of the wall I'm touching? I tried looking into this earlier since I needed the walljump to be opposite to the wall direction but I just couldn't figure it out at all, ended up giving me a headache
how are you determining that you are touching a wall in the first place? because however you are doing that will determine how you get the normal
so you are using OnCollisionStay. you can get the first point of contact from the Collision and get the normal from that
do I add something to the OnCollisionStay part then?
yes, that is the only place you can access that Collision info
you're also already accessing the normal for each contact point . . .
i dont really know how to apply it to other things
im not even sure what the first step here would be
trying to transition to FP, how do I get the bullet to rotate towards the center of the screen (bulletEnd)
you'd need to get a world space position for "center of screen"
one simple way is just something like:
myCamera.transform.position + myCamera.transform.forward * distance```
or a cuter way: myCamera.transform.TransformPoint(Vector3.forward * distance)
Hey, I can usually drag the game window from the Unity Engine to another screen. But when I get over the edge it's back to the right. How can I drag it back to another desktop?
Ofc not i am testing it at build
Drag it off the dock first to make it a sub-window, then move the window to another screen
I don't think so
Guys i have problem with changing my game resultion the first debug showing the desird resolution but after doing screen.SetResulution nothing changed could it be relate to display mode or somthing can somone help me
Screen.SetResolution(resolution.width, resolution.height, false);
Debug.Log($"ِCurrent resolution height {Screen.currentResolution.height} and width {Screen.currentResolution.width}");```
https://docs.unity3d.com/ScriptReference/Screen.SetResolution.html
A resolution switch does not happen immediately; it happens when the current frame is finished.
https://docs.unity3d.com/ScriptReference/Screen-currentResolution.html
https://docs.unity3d.com/ScriptReference/Screen-width.html
https://docs.unity3d.com/ScriptReference/Screen-height.html
Also test it out in a build, not the Editor
can anybody help me? when I write some line of code, some of the words won't highlight. should it be a problem, and if it is, what can I do to fix it?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Make sure you have the unity preset installed into your vs ide
For vscode you need to install the necessary dotnet sdk and install the unity extension.
how do I find the preset
There is a guide right there. And it isn^t called a preset btw
Oh k
It turns out I didn’t use Visual studio as my external script editor, do I regenerate project files?
Yes, for good measure
Extensions tab in vscode. Follow the guide
It's called an extension
They are using vs apparantly
Alright
Just click on "Unity compatibility" or whatever its called
I haven't used vs in a while
Are you talking about the Unity workload?
Yes
Ok, that is part of the guide
I'm aware
Preset was just confusing because neither the workload nor extension are called that.
Don't wanna make things confusing when they are already following a guide
Not, really code, but pretty sure my script is what is causing this... My healthbar is... dissapering from the Canvas, just after the shake effect that moves the whole UI when taking damage
Yes, I used quotations to make it clear for the person who called it a preset
A video would be useful
I'd say just let them follow the guide next time
And some source code
How can I detect a single mouse click rather than every frame that the mouse is held down
But it only affects the healthbar and if I move it slighty it shows again, as if I was covered by a mask that makes it transparent there or something like that... But I don't know what is causing that...
I don't really have anything to record, I would just show some images if you think it helps
Input.GetButtonDown
Sure, that would work
Give me a sec, I am with something else, I will explain it better in a moment
not working
Thats "Input.GetKeyDown", edit: nvm he referenced an axis
What axis type did you set it to?
it was set to x
what do i set it to
Joystick
I just need a mouse click
then why are you using Joystick button 0
Joystick Button 0 is not a mouse click
thanks anything else?
Do you know what a mouse is or??
should be ok now.
That should do it
L is a weird name for it
l as in left click
An axis can be any default trigger
You can change the primary trigger fir the axis to be ctrl or shift or anything like that
You're welcome :)
how would I go about rotating a prefab before it has spawned or set it's rotation before spawning
Instantiate takes a rotation parameter
yeah
don't worry about the 4 numbers
Quaternion.Euler(x, y, z)```
ooohhhh
Or Quaternion.AngleAxis(angle, axis)
and i can use that as the rotation parameter instead of quaternion.identity?
You can use any Quaternion as the rotation parameter
Yes
Quaternion.identity is the default rotation. Or just 0,0,0
Instantiate(Prefab, PrefabPos, Quaternion.identity);
is void Start() the first frame when loaded into a scene?
Yes
yeah i got it working thanks so much
No problem
and void Awake() is?
Basically the Monobehaviour's constructor
Runs before any Start methods, useful for assigning data before running it
Called when the script instance is first loaded, and only loads once
Start is for every time the script instance is loaded
okay thanks
was watching this as you asked\
lol
is the tutorial good?
whats the simplest way to detect mouse hovers on ui elements
some of it is meh but I'm a super beginner and some of these basics i needed
the IPointerEnterHandler and other event system interfaces
u planning on making an animation based on if the user is hovering over it?
alright
no
oh ok
EventTrigger component and PointerEnter/PointerExit events
Both start and awake only run once in the lifetime.
thanks, would this be onpointerenter?
Yes. My bad
Yes
Hey guys.I used for loop and sample height to spawn a stone on a terrain.I used the same way to spawn rabbits just without a for loop.But this time the stone spawned like 200 units in the air or inside the ground.I couldnt get the correct Y coordinates
Make sure this is your script class ```using UnityEngine.EventSystems;
public class ExampleScript : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler```
why are you hardcoding the ranges like that and why are those numbers so gigantic?
they are hardcoding rn for testing
Do they spawn in the air because you used such massive numbers?
its 10000 cus i need to randomly spawn stones,trees etc in my terrain cus if mass placed the scripts wont work
i dont think so. its just a number
I'm not sure what the problem is. Do you want them to fall down?
for how many times the loop is to be repeated
nope just stay there
i mean on the ground
A number that determines the spawn coordinates...
oh those numbers
they are the X and Z coordinates
not the Y coordinates
The Y coordinates is to be found through this
Try logging what Ycoords is set to
And perhaps check what transform.position results at, and see if these are proper coordinates you expect them to be
My guess is that this is not what you expect
Ah I see. Didn't catch that
Then consider drawing spheres instead
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(this.transform.position, 1);
}
Although won't the for loop add 1 to the y coords 10000 times?
i spawned 10 rocks 1 of them spawned at y lvl 0 and rest all of them at Y lvl 182 for some reason
why the Y coords?
No, because if you read the line above that it assigns the value
Ah right. My bad
but then wont it run the code to get the Y value everytime it repeats
this happened for some reason
My guess is that they should just replace transform.position with SpawnCoords but it doesn't hurt to teach basic debugging
why wont they show up in the inspector?
static
Remove static
alr ty'
Unity does not support providing static as an assignable field in the inspector. Instead make it instanced
I put on spawncoords now it gives totally random coordinates
my plan is to put all the references to the player one script, then have all the spawners take it from there so i dont have to manually assign that everytime, and also maybe eventually make the spawners a prefab, so ye
why are you making them static?
would i need a singleton pattern for this?
so i can do my plan, but seems that wont quite work
Singleton, static properties
If you can make this object a singleton, that probably means you can make all of the contained classes singletons instead. If those objects are not good candidates for singletons, neither will this one be
i'm making a first person game so ofc I made my cursor dissapear. but I want to add a new one that's always centered how do I do so?
basically what I want is a crosshair
you just create a canvas and put an image centered
#unity3d #unityfps #fps
I am back with another Unity FPS tutorial! And this time we will be looking at how to create a crosshairs for your FPS game.
I used substance designer to create a texture consisting of a few crosshairs, Substance designer is quickly becoming my go to for creating textures for use in my game development projects. The ea...
well there will only be one player so id say they would work as singletons
right?
I can't really answer if these are proper singleton candidates. Are all of these objects cases where there is always exactly one instance of these objects in every scene?
id say yea, in every scene where this singleton will be used, there will be the player
If everything this script would have referenced can be made a singleton, just make them the singleton and reference them that way
What is this error?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnScript : MonoBehaviour
{
public GameObject pipe;
public float spawnRate = 2;
private float tomer = 0;
// Start is called before the first frame update
void Start()
{
spawnPipe();
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer = timer + time.deltaTime;
}
else
{
spawnPipe();
timer = 0;
}
}
void.spawnPipe();
{
Instantiate(pipe, transform.position, transform.rotation);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnScript : MonoBehaviour
{
public GameObject pipe;
public float spawnRate = 2;
private float tomer = 0;
// Start is called before the first frame update
void Start()
{
spawnPipe();
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer = timer + time.deltaTime;
}
else
{
spawnPipe();
timer = 0;
}
}
void.spawnPipe();
{
Instantiate(pipe, transform.position, transform.rotation);
}
}
!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.
configure your !IDE so you don't make silly syntax errors like the ones you have demonstrated
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
What is an !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
It's a bot command that brings up the instructions you didn't read
I started today
the world may never know
for how to configure your IDE
What is an IDE
Integrated Development Environment
The thing you type code in
it has syntax highlighting, intellisense, project management, build tools, etc
wouldnt it be easier to just make one, and in there i collect all the scripts i want to reference
idk anymore
i still dont understand
the documentation for all these things doesnt help me get what im meant to do with them
I've done it now
Okay, so do you have red underlines in your code?
what im wondering is what you were using when you created that code...
C#
Ah, Didn't realize i could scroll down
how can I detect a mouse hover over a button/image ui
cause it already detects as it highlights
before learning the unity API, you need to know C#, to learn C# you need an IDE and know what an IDE is
you can add event trigger component to the button and call custom methods
ohh thanks
use the event system interfaces like IPointerEnterHandler
and is point enter the correct one
The text editor, not the language lol
where do i open det animation rigging i have downloaded it?
VS Code is a text editor but has syntax highlighting and intellisense tho...
using UnityEngine.EventSystems;
public class ExampleScript : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public void OnPointerEnter(PointerEventData eventData)
{
}
public void OnPointerExit(PointerEventData eventData)
{
}
}```
should have a brand new button at the top
It's just errors
you have to install the net SDK
i dont understand the paramters pointeventdata eventdata
That happend last time, but not this time
Where can i download
you can go to the definition to learn what it returns...
or look up the docs
i did and i still dont get what the paramters are
Found out
It's one parameter. PointerEventData just holds the information of the pointer event that triggered the method. Such as the position, what gameobject it entered, etc. You don't really have to know
Yes now It's showing red lines
That should give you some hints as to what the problem is
But i still don't understand
you need to install c# before using c#
You should learn c# before continuing
where would the script go, inside of the UI which you want to detect mouse hovers for? Also does that mean it doesn't need any parameters (like update or start)
Do you have a tutorial?
there are beginner c# courses pinned in this channel
Ok so in order: 1 is the interface in edit mode; 2 is the layout; 3 is the UI in game before getting glitched; 4: is the bar missing after taking damage and doing the shake effect; 5 is me changing the resolution to reload it and now it shows; if I take damage again is goes missing again. 6 is me moving the main layout container a bit, it makes this weird mask-like effect, it does no affect anything else in the UI aside from the healthbars
where
in the pinned messages . . .
Guys, I've been workin on it for like a week (my first game) and all drawings are made by me (I suck at drawing 😦 ), can you suggest something to add because I don't have a lot of ideas rn, maybe with some help I'll know what to do
check ur spellings homie.. you have tomer you have timer you have spawnPipe() void void.
its all over the place
@cunning rapids
Why does the res on your numbers get so bad in the 5th pic? I thought you only changed the bar's res
Yeah, to a lesser res XD
Take a look at your spawnPipe function. Do you notice a problem that none of the other methods have
It sounds like whatever shake affect you're applying thru code is what's making this happen
If you make and play an animation it would be a lot easier
Tween it
if i am using destroy on a variable does it also destroy the variable
itselg
not just it's contents
wdym by "destroy the variable"? the Object.Destroy method just destroys a UnityEngine.Object. it does nothing at all to your variables
pretty sure u cant destroy a variable at runtime
oh okay well i used Destroy()
yes that is Object.Destroy
This is what causes the shake, it worked before
I don't think I have changed anything...
i cant reference objects that are in the scene when it comes to singleton patterns 🫠
This code is very framerate dependent
prefabs cannot reference in-scene objects. nor can you drag a reference from one scene to another
https://unity.huh.how/references/prefabs-referencing-components
It is, I don't think it matters, it always resets to the initial position anyways
where does `startincContentPanelPosition come from
why wouldn't that be valid
cause my script is bugging
Debug.Log is cosmetic at heart, but useful in the real world
GetComponent<Renderer>().material.color
Does that mean take a rendering component?
thanks for your wisdom
ill try it
https://paste.myst.rs/2se0wu71
can someone tell me why only the heavyAttack input actually does all the stuff in my coroutine, it's acting really weird
a powerful website for storing and sharing text and code snippets. completely free and open source.
Nice colors
How do you do this?
the colours?
the coroutine is getting called in both cases but not all of the stuff is happening
Yes
its called halycyon theme
Thanks
if heavyAttack was not pressed this frame then player.currentState is set to PlayerState.idle
Does anyone can answer?
Yes, you are accessing the material color of the renderer component
no the heavy attack is working, but the lightAttack isnt
oh wait
Thanks
did you finally realize what i was getting at?
yep
ty
I'm back hello
I'm pretty sure you have to shake the health bar along with the background
It looks like the background overlaps the bar
Idk why but when I press the A and D keys sometimes the character defaults back to the idle state but moves while in idling
SetEquipment(GetEquipment(GetCurrentEquipment(cell).itemData).inventory, true);```
```private void SetEquipment(GameObject gameObject, bool active)
{
if(gameObject != null)
{
gameObject.SetActive(active);
}
}```
i get a NullReferenceException: Object reference not set to an instance of an object on this line if(gameObject != null)
Is that actually the line the error is on?
its on if(gameObject != null)
no way null check wouold throw null ref would it
That line cannot throw that error
Did you make sure to save all your scripts and clear the console?
why is your local var named gameObject :\
that was just for testing
Okay, that one can be null. I think it's due to Unity's weird == null override thing that's been confusing as hell for like ten years. Try if (gameObject is not null) instead. Also change the name of that variable
u know the model i pass into the method
it can be null
like this SetEquipment(GetEquipment(GetCurrentEquipment(cell).itemData).clothingModel, true); returns either a null value or a game object
Right. And Unity does some fucky stuff iwth GameObjects and == null, which is why I'm suggesting you use is not null instead
i tried it
same thing
It looks like your IDE has something to say about that if statement, hover over those three dots. What does it say?
but the is not null would do a pure null check and wouldn't be true if the object is destroyed whereas the current comparison to null should work just fine
show the full stack trace for the error
Yeah, you're right. != null should be more inclusive, not less
Can you share the !code of EquipmentManager (use a bin with line numbers)
📃 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.
yea..
yeah that makes more sense. there are several objects on that line that could be null
So, after we asked you twice what line it was on you gave us two different answers, neither of which were correct
sorry about that
Why did you not just actually check instead of guessing twice
Would I need to post the code in links if its up to about 70 lines of code?
cause this works
Store things in variables
that's not the null part though. that final item wouldn't be what throws.
Store GetCurrentEquipment(cell) in a variable. Then store the itemData in another. And so on
it is either cell, GetCurrentEquipment(cell) or GetEquipment(GetCurrentEquipment(cell).itemData that is throwing an NRE
also for the love of god break that up into multiple lines so you can reuse the objects and so it is more clear what exactly is throwing
https://paste.ofcode.org/7xe5XwBWKPRFYxCHnR7tAS This one keeps doing this bug where it allows the idle state to animate will moving.
you probably need to check your transition settings in the animator
Looks like you're basing your movement speed off of the Vector, but your animation based on key press/release. If your axis has smoothing, it doesn't instantly become 0 the frame you release it, it slowly goes back down to 0. So you immediately change animations but there's still some input left on the axis. You should stick to one or the other
Use the input vector for everything
what's the difference between IsTrigger being checked and not being checked?
Trigger colliders are not solid, things can freely pass through them, but they still provide physics events (OnTrigger instead of OnCollision)
I have a movement system for 2d space ship that follows the mouse for direction. but if you stop moving the mouse and it reaches it than to sprite shakes back and forth. how can i go about stopping that
oh so the same thing as colliders but you don't touch them?
I see, thank you
For the most part, yes
check distance from worldMouse, if too close don't do the flippy thingy
@rich adder and those videos have been a huge help im still working through them
i fixed the nonsense from last night since I didn't even realize those were functions you were telling me
alright this works
thanks
Ohh ok thank you!
please learn how to use local variables so you aren't calling the same exact method 3 times
It looks like you can pretty cleanly set that animator parameter to horizontal.magnitude, assuming the parameter is a float and can accept decimals
why when i die then respawn and dash this happens (it dashes me backward opposites the way am moving)
player movement code https://codeshare.io/ApKxyw
player death code https://codeshare.io/MkjxJe
Please for the love of Gaben store that GetEquipment result in a variable you're using it three times
lord gaben
isn't lord gaben the creator of steam
Seems so, but I am pretty sure the whole container is moving so...
I don't know how anything could be in front....
i am very much so confused on why you chose to send a picture of you replying to me and yet it meant you sent it as text but I wasn't pinged twice and only once for this reply, am I going insane?
eh my original reply was text but deleted by Dyno Regex
so I got lazy and sent the SS of it
I want to make something that stores an array of prefabs how do I do so?
Regex filtering. It was too short
perhaps by using an array?
public Transform[] Myprefabs
yes I tried doing so with
public PrefabType[] cardSprites;
but it won't work
thanks
this works fine, what you mean " wont work"
Where the 0 and the 1s are?
do you have a component called PrefabType? if so, that would absolutely work
it won't spawn them
no
show entire code
well no wonder it didn't work, you can't just use things that don't exist
Yes, just set the animation parameter directly to the magnitude of your movement vector
Well that is an entirely separate issue
did you figure this one out ?
im working it out now and going slow
Use the suggested Transform[]
Or use a component that exists. Like I have a Unit[] of prefabs for my various Units that I can spawn. This means I MADE a class called Unit. Thus the type exists
okay so if I want it to spawn I go Instantiate(transform); or Instantiate(cardSprites);??
kinda stuck but I'll get it just need to figure out the best way to implement it
Neither
no..thats not how indices work
there are beginner c# courses pinned in this channel if you do not understand how arrays work
Valve created steam. Gabe newell is the founder if valve
I understand how an array works. but now how instantiate works😭
and you're replying this to me why?
Your error is only with how arrays work
Instantiate WAS fine if cardSprites was a variable
Instantiate is just a method like any other method. it takes a single object as its first parameter, not an entire array
you pass the specific / random one you want from array
The ONLY thing you need to do is access the array properly
use a for loop
ohhh so instantiate(transform[0])??
It seems like they want to instantiate a specific item from the array
why is your array named transform ?
I cant find magnitude for some reason. When I type it in nothing comes up
cardSprites[0]
Do I gotta set it?
@maiden yarrow You have to access an array by its variable name, not the type of course.
Again, this is a basic c# issue with arrays.
Not related to Instantiate
Oh wait, it's a 1D axis not a 2D one, so it's just a float. No magnitude needed
just use the value
Instantiate(cardSprites[theIndex])
So just use horizontal?
Yeah that should be fine
It works but only on the d key. The a key does not want to animate to the walk state
Oh, right, you probably don't have the animation set up to accept a negative. Try Mathf.Abs(horizontal) instead
Because I assumed you corrected "gaben" to valve
Even though they're both true
I believe they were trying to correct steam to valve
Ah my bad
It worked! Thank you!
Camera.main looks for a game object tagged with MainCamera and tries to get a Camera from it
(the camera is cached, so it doesn't literally do a find-with-tag and a get-component every time you use it)
are you having a problem?
How do you know? Are you checking with debug.log or is your var public?
@rich adder nope i failed back to my videos
thats.. just.. how i understood what they said
how can i refresh a canvas through script?
oh i thought you meant the var wasnt being set properly oops
wdym by refresh?
wdym
like u know scroll rect
and other canvas components
i need them to update
in a specific moment
tried creating a dead zone and turning the rb.velocity to 0
wait a second i need to use the magnitude I think
Hello. I am unable to build "Mobile 3d" template on an android device. I can successfully build regular 3d templates on android. Error thrown :-
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2022.3.20f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\build-tools\32.0.0\package.xml. Probably the SDK is read-only
I have installed adaptive performance. This is empty "Mobile 3d" template , via Unity Hub. And I can build non-mobile teplates on android (without and with adaptive performance)
what is the problem you're trying to solve?
i'll show u in a minute
https://docs.unity3d.com/ScriptReference/Canvas.ForceUpdateCanvases.html can be used to forcibly update all canvases
send current code
use link
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
<i wish more ppl would kill their embeds>
hi, im having a bit of an issue with triggers, objects are passing through each other, everything seems to be correct in the code, but nothing in the event or script is actually triggering, this was working before i started trying out the new input system, i must've ticked, removed, or unticked something to produce this problem but can't for the life of me figure out what the issue is! 😂
thank you, ill give it a read and go through now
first , why isn't your direction Normalized()
also thought you mentioned a sprite, if you don't want it to move instead of setting vel 0 just make bool and exclude input
u see how its not getting updated?
i had to minimize the window
for it to update
that sounds more like a problem with your UI layout
for example -- perhaps you've got ContentSizeFitters in places they do not belong
Where exactly. i had it at one point but i believe it was giving me an error
probably
most likely being my fault at the time
That UI on the right should be layout groups all the way down
- Inventories <-- VerticalLayoutGroup
- Inventory <-- VerticalLayoutGroup
- Title
- Grid <-- GridLayout
- Inventory <-- VerticalLayoutGroup
bah, sec
Vector2 direction = new(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
direction.Normalize();
transform.up = direction;
If you ever see this, your UI is set up incorrectly!
oh
Do you mean to have one very large scroll area?
so that you scroll up and down to go through different kinds of inventory grids
i could just have this
and it would work
but i want the categories
like Chest, Legs
etc
thats why i had it like this
with extra content size fitters
- ScrollRect <-- ScrollRect, no layout group
- Mask <-- Mask, no layout group
- Content <-- ContentSizeFitter, VerticalLayoutGroup
- Head <-- VerticalLayoutGroup
- Title <-- no layout group, just a TextMeshPro to display the word "Head"
- Grid <-- GridLayoutGroup
- Grid Cell <-- no layout group, just an image or whatever
- Content <-- ContentSizeFitter, VerticalLayoutGroup
- Mask <-- Mask, no layout group
The default "Scroll View" preset is roughly what you need
for some reason some boxes were unticked
you just need to throw in the content size fitter and the vertical layout group on the "Content" object
The ContentSizeFitter reszies its own object to fit the content in its children.
The VerticalLayoutGroup asks its children about how much space they want, then asks for at least that much (plus more for spacing, margins, etc.)
It's vital that you have layout groups all the way down.
default was unticked, re ticked and now works (:
If each category has a ContentSizeFitter, then it will try to resize itself
im so confused
rather than just asking its parent for the space it needs.
so remove the content size fitters?
I think this was last night when I was trying to understand exactly what normalized was and in this mouse movement set up I couldnt notice a difference and I forgot to put it back
Correct. Your UI should be laid out like this #💻┃code-beginner message
but your right since I am only using it for the direction It should be normalized if I remeber correctly
normalizing makes the length a max of 1
which is very useful for only needing direction for example as it keeps it consistent
Yes that's what I was reading l, I was taking it out and putting it back in to see if I could tell the difference cause I don't fully understand the concept
imagine you pass direction as is to a weapon shooting bullet, the bullet will now be faster depending how far the distance is from firepoint to mousePos for example
its still giving me the warning
on the content size fitter
its because of the scroll rect
when i disable it its gone
go to GameObject -> UI -> Scroll View
observe how that is laid out
You are missing the intermediate "Viewport" object.
in general, that menu will set up a bunch of gameobjects in a default config that should be functional
look at the differences between the two numbers
note that this is a #📲┃ui-ux problem, so we should move the question there
it's not a code problem
oh wow
Let me see if I understand correctly. With normalized my direction max is pretty much always 1. Without it if my direction max is let's say 10 that messes up all my movement equations
when you don't normalize there is no max, you're getting the full "length"
a normalized vector is dimensionless, and of length 1
https://youtu.be/f6KaJHUfE2M?si=2ZpexB-kt8U3_Myr
Can anyone halp me download the package in this video?
Learn how to optimize the performance of your game by automatically combining meshes, significantly reducing draw calls using the free HLOD tool from Unity. Hierarchical Level of Detail is a great tool to boost the FPS of your game, especially when you have large view distances with complex geometry!
💸 Ongoing sales 💸
⚫ Check out the latest Hum...
Now I understand! My test screen was so small I couldn't see it but that makes perfect sense now
if your displacement vector is 5 meters right, then the normalized vector is (1,0) dimensionless
aint watching a whole 12 min video to find the asset,
just link to the spot or just screenshot it
It is a github repo
keep track of your units carefully.
World space is in meters. Screen space is in pixels, and canvas space is in unscaled pixels. They are not the same
so just download it
How?
big green button on github page
Maybe that's why my dead zone idea near the mouse isn't working
and the program doesn’t understand units, only numbers. so you need to keep track of units
ehh prob just bad logic there
How to add it to unity
did you read the instructions on the Github repo
@rich adder give me a hint
Ye it told me to clone the thing
And thats it
yeah, so if your canvas is rescaled based on 720 p, and your screen is 1080p, then a distance of 10 unscaled pixels on your canvas (canvas space) is 10 * 1080/720 pixels in screen space. Canvas has a method to give the current ratio.
yes you need Git and know how it works to clone
or just download the repo
There's literally an entire how to download section in the repo readme 😭
download the zip
pull the folders into ur project.. (check documentation) to set up anything thats missing
or else learn github and just clone it
ah, yea may be best to just clone it.. readme says theres submodules needed for a fully working project
for smart strings in localization, how to set a number to appear unsigned?
Make it smart and then format it to be Math.Abs
I am using the signal to decide if the number will jump to left or right
I will try this
Sure. Let me know, I'm interested to see how you did it using those conditionals (never used them in localisation before)
Hi guys I am having trouble with my ability system, I dont really know how to face it, the thing is I want each of my characters to have different habilities (take pokemon attacks as an example), How could I program that, any ideas? Ive been stuck with this almost for a week please help
Same thing I wrote earlier, interaces, etc.
But yeah, as navarone says, it ain't a simple thing
It aint bro, Im really lost
thanks for yesterday btw I went to sleep
Each of my Characters in roster has an scriptable object (EntityData)
Ahhhh
I worked on the interfaces thing yesterday and I was really lost
https://www.google.com/search?q=pokemon+ability+system+unity lots of results here
I can describe the way I would do it, in a bit more details if you want
But generally there are a lot of resources online
Which you can learn from
yes, I searched a lot yesterday
if you want I can describe my progress
and If it is possible you can help me
Describe what you've already got, and what kind of goal you have in mind
Okay, thanks, let me tell you
I have an "ActivateAbility" interface with which I´ll describe the effect of each hability in separate scripts with classes that describe these abilities. Example: class Fireball:IEffects {ActivateAbility(){//ability behaviour}
but the thing is how can I make sure that every character has some specfific habilities and how can I organize it
the goal is to create a system in which every character has access to 3 unique habilities which are managed by a boostManager I already created
Ability systems are complicated because you need a consistent way to interact with many different kinds of abilities
Think about a MOBA, like Dota 2
There are self-targeting spells, unit-targeted spells, point-targeted spells, and vector-targeted spells
personally, I dealt with this by just making one kind of "spell" that listed the ways you were allowed to use it
and one kind of "Spell Target" class that covered all of the bases
it'd just throw a runtime error if you did it wrong
e.g. if I tried to cast a unit-targeted spell with a SpellTarget that didn't actually have a unit in it
I'm going through something similar again in my current game (a survival horror game, not an RTS)
each "thing" in the game is an Entity with Modules attached to it
and Modules give you a list of Activities they let you carry out
Hey, im trying to generate a class on the fly by a codegenerator, this is my template:
public static readonly string ComponentEnum = @"using UnityEngine;
public enum Component : int
{
Test,
{0}
}
";
Now i try to do string.Format on it but it seems it sees the template as malformatted because it has curly braces, any way to solve that?
most of the Activities just tell the Entity's state machine to enter a state provided by the module, like "Try to go into the 'Open Door' state"
At some point I'm going to start adding abilities that aren't just "press F to pay respects", and I'm not really sure how i'm going to handle things like area-of-effect targeting!
It's difficult stuff.
the Modules are given references to whatever other Modules they need to carry out the ability
so a module for picking up an item holds a reference to an IK module
(inverse kinematics, for reaching out and touching a target)
I've been trying to get as much as possible out of my Entity class
the thing is I am making a fighting game (take Street Fighter for example) and each of the characters in roster has their unique habilities but these are very different one from each other
Why not use string interpolation
Ive thought of making one script for each ability but I dont know how to assign the abilities of each character to them in order to use those specifically
Because I put the templates in a seperate class (file), the example i posted is a fraction of what the generated code will be in the end
Ive been messing around with it a lot of time but still dont know what way to develope it
Ah yes that makes sense. I'm not sure but like 80% sure at least that you can double the brackets to escape them in string.Format
Let me know if that works, I'd be interested. Haven't used format in a while :)
Oh yeah, {{ worked
Cool!
Thanks
Can I ask here for help?
some one know how to make grid cell size changed based on resolution ?
why would you need to change the size of your grid based on resolution?
what you probably want to do instead is actually just change the orthographic size of the camera so it always sees the same amount of content no matter the resolution
as u can see i wanna resize them instead of changin columon and i am to lazy to make scroll there
My brain isn't working at full speed today, but here's how you could possibly do it:
Ability - ScriptableObject with an EffectWrapper[] array, could be maybe unwrapped into a [SerializeReference] IEffect[] but not necessary
IEffect - interface with an Apply(ICaller caller) method
ICaller - interface with any kind of properties and methods you'd need when making different effects implementing the IEffect interface
EffectType - enum, used to select the kind of effect the ability has (could be for example Projectile, Kick, Punch, etc)
EffectWrapper - a wrapper for [SerializeReference] IEffect, with an additional field of EffectType used in OnValidate() or (preferably?) ISerializationCallbackReceiver to instantiate a correct type of effect into your IEffect field
Then just make an Ability[] array for your characters - or a special class/struct with a fixed amount of Abilities if every character has the same amount of these - and assign your Ability SOs into these fields.
I don't know if it's the prettiest way there is, but it should work and be flexible enough to introduce a variety of different abilities. Analyze it and decide if it works for you or not
yes
one option is to just completely commit to everything being an "ability"
although, that doesn't really work if you don't have any experience yet
but it's what I've gone for multiple times in the past
Almost everything in an RTS I was prototyping was an ability
building a house, mining a resource, attacking an enemy, using a spell
I need help with an issue, hopefully an easy one, can someone help please?
Dont ask to ask, just ask 😄
check the pinned documentation in #📲┃ui-ux to learn how to properly scale your UI
I added crouching for my character using the Unity Input Action System. I created an OnCrouch method to manage the input actions and an IsCeilingDetected method to detect ceilings and keep the character crouched when one is detected. everything seemed to work fine: pressing the crouch button made the character crouch, and it stayed crouched when under a ceiling. However, I encountered an issue: when I moved away from under the ceiling with the crouch button released, the character remained crouched until I tapped the crouch button once (The Crouch button is hold not toggle). So the character becomes stuck in the crouched state if the collider detects a ceiling, and it wouldn't stand back up automatically when leaving from under the ceiling with the crouch button released until I tap the crouch button once. I can't seem to figure it out no matter how much I squeeze my brain.
Here's the code: https://hastebin.com/share/mucowunipu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
wow, Im trying to understand it, thanks a lot for your time! @Fen as well
you only check if it can uncrouch one time when the button is released. you need to start checking when it is released and keep checking until it has uncrouched or the crouch button is held again. for that you would need to use Update
I try to do a Tower-Defense game but my problem is the enemy dont move. I realy dont know why. LevelManager Script: https://gdl.space/ralazibeji.cpp EnemyMovement Script: https://gdl.space/axipahukut.cs
Nothing in that EnemyMovement script seems to be moving anything
What should I call in update exactly? (I'm a noob at programming)
do the exact same logic that you have in your "on crouch" method.
you just need to do that every frame, not only the instant that you let go of crouch
the thing is that each ability has one effect not more than one
Rly? I just followed a tutorial
you can set a bool to indicate if the player is trying to crouch or not
Show the tutorial
did you forget to watch the part of the tutorial where they made anything move?
Learn how to make a 2D tower defence game using Unity. Welcome to part 2 of our 2D tower defence tutorial, in this video we focus on adding an Enemy AI and Enemy Pathfinding to our game using Unity!
Next Video: https://youtu.be/5j8A79-YUo0
Previous Video: https://youtu.be/WH8b2ihk_YA
Playlist: https://www.youtube.com/playlist?list=PLfX6C2dxVyLz...
No
timestamp 8:30
Then simply have an EffectWrapper instead of an EffectWrapper[] in the Ability SO (you could also ommit the EffectWrapper class entirely and move that logic to Ability)
Number of times it wasn't exactly like the tutorial: 152
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-3-26```
It was actually as simple as doing this {0:#;#}
that makes the number into one digit minimum, so it never adds more digits or sign
what is the ICaller for?
that is the step I dont really get
The ICaller is your character, it's an interface containing methods and properties which help with 'using' the ability
hi, inspector likes to select all list bluse when i try to change 1 value.
is it a some problem?
i just made poblic nonReordable list a i dunno what's wrong with it
sorry, I still dont get it
just a bug, like you've click and held to highlight text.. might try right clicking.. in an empty space somewhere.. maybe reset ur layout.. might even need a restart if u cant get it to stop
I Already have a bool checking for when the player crouchs and uncrouchs, so what should I exactly call on Update?
Should I like call OnCrouch in update?
no, because OnCrouch is supposed to be called when you press or release the button
ICaller can have a ShootProjectile(int amount) method, which could be invoked from within an effect such as
class ProjectileEffect : IEffect
{
[SerializeField] int m_amount; // Just an example
public void Apply(ICaller caller)
{
caller.ShootProjectile(m_amount);
}
}```
How ShootProjectile is implemented is up to the character
Could be a single projectile or a few from each hand
Move the logic that checks for an obstruction out of OnCrouch. Make OnCrouch just set a bool that tells you if the player wants to crouch.
Check if you can actually do what the player wants in Update.
anyone feel like guiding me on where to look at how to create a grid for A* pathfinding using code?
Oh, okay, I think I get it
Alright, I think I get what you are saying, thank you.
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E)) GetComponent<Renderer>().material.color = Color.black;
if (Input.GetKeyDown(KeyCode.Space)) GetComponent<Renderer>().material.color = Color.white;
if (Input.GetKeyDown(KeyCode.Tab)) GetComponent<Renderer>().material.color = Color.green; Debug.Log(transform.position);
if (transform.position.y < 5) Debug.Log(transform.position);
if (Input.GetKeyDown(KeyCode.O)) transform.position.y = 5;
}
}
Help please
Doesn`t work
- For the love of all that is holy cache your get components
- What about this "doesn't work"
yes your line here is wrong:
transform.position.y = 5;
that's not valid C#
Is your IDE configured?
You cannot both get and set an individual component of a vector. You need to either set the entire position at once, or store it in a variable, modify it, and put it back
Maybe
Ohh. Now I feel stupid
. Thank u
I tried that
Okay so show that
1 minute
Hey, I'm trying to learn the new input system and can't get it working, I set up the controls on the manager, set up the component and wrote the function OnDown but it's not printing anything
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LocomotionState: State
{
public PlayerStateManager stateManager;
bool started = false;
ControlsGame controlsGame;
private void Start()
{
controlsGame = new ControlsGame();
}
public override State RunCurrentState()
{
if (!started) StartState();
UpdateState();
return this;
}
void StartState()
{
started = true;
}
void UpdateState()
{
stateManager.commonStateLogic.MoveWithInput();
}
void OnDown()
{
print("OnDown");
}
}
What is State? Did you attach this script to the same object as the PlayerInput component?
u cant set a single property of transform
You cannot both get and set an individual component of a vector. You need to either set the entire position at once, or store it in a variable, modify it, and put it back
that means .x, .y, or ,z
by cache components you mean putting them in Start or FixedUpdate?
No, does it have to?
One of those is certainly the case
"cache" means store for later use
What is that?
Yes, it will only send messages to scripts on the same object