#💻┃code-beginner
1 messages · Page 805 of 1
hello guys, new here!
Use the built in one unless you have a very very specific usecase
build in
I'm making my own rig system that uses pivot points for anims and a centralized root part for raycasting the character collisions
Are you doing this for a learning/asset creation point or just reinventing the wheel for the sake of it?
well then use the standard animator until that doesnt work for you anymore
I can also set ground types too and plan on adding a friction setting for them
is there a way to differentiate wall tiles and ground tiles in a tilemap for game logic?
In terms of what?
Texturing or hitbox?
Could use collision layers
or tag
or check if the surface position is below a certain threshold of the player
oh, sorry I should've been more detailed, I'm trying to do it for hitboxes, so the player can jump when touching a ground tile but not when it's touching a wall tile
@silk night just fyi if youre interested. unity6.3 didnt fix my problem, but i tested with a RigidBody + CapsuleCollider instead of a CharacterController, and this works perfectly. time to rewrite my movement code I guess 
How do you set tags/layers for individual tiles? I've been looking around and so far I can only seem to set the tag/layer for the entire tilemap
this is a code channel, ask in #🖼️┃2d-tools
Is it a whole mesh or individual?
tiles aren't gameobjects, the tilemap is
you'd have to Tag them your own way by using scriptable tiles
I'll look into that, thank you for the help!
Anyone know what causes camera to skip randomly?
not without more info, no
I'll send the script I made
private void UpdateCamera()
{
Transform target = (CameraOffset <= 0.1f) ? Neck : Character;
Quaternion rot = Quaternion.Euler(pitch, yaw, 0f);
float OffsetX = ShiftLockOn ? 1.5f : 0f;
Vector3 OffsetFix = new Vector3(0f,CameraOffset <= 0.1f?0.25f:0f,CameraOffset <= 0.1f?-0.125f:0f);
Vector3 offset = rot * (new Vector3(OffsetX, 0f, -CameraOffset) + OffsetFix + HumanoidCameraOffset);
GameCamera.rotation = rot;
GameCamera.position = target.position + offset;
bool showHead = CameraOffset > 0.5f;
Neck.gameObject.SetActive(showHead);
if (Input.GetMouseButton(1) || CameraOffset <= 0.1f || ShiftLockOn)
{
yaw += Input.GetAxis("Mouse X") * sensitivity;
pitch = Mathf.Clamp(pitch - Input.GetAxis("Mouse Y") * sensitivity, -80, 80);
yaw%=360;
pitch%=360;
}
}
not just the script but anything else relevant, if a video can be done too
This is latest update too cause I tried to see if it was update related
📃 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.
The camera works but for some reason it randomly skips to some random rotation and jumps
!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.
just use the links provided so at least the block of code has some context
```cs
private void UpdateCamera()
{
Transform target = (CameraOffset <= 0.1f) ? Neck : Character;
Quaternion rot = Quaternion.Euler(pitch, yaw, 0f);
float OffsetX = ShiftLockOn ? 1.5f : 0f;
Vector3 OffsetFix = new Vector3(0f,CameraOffset <= 0.1f?0.25f:0f,CameraOffset <= 0.1f?-0.125f:0f);
Vector3 offset = rot * (new Vector3(OffsetX, 0f, -CameraOffset) + OffsetFix + HumanoidCameraOffset);
GameCamera.rotation = rot;
GameCamera.position = target.position + offset;
bool showHead = CameraOffset > 0.5f;
Neck.gameObject.SetActive(showHead);
if (Input.GetMouseButton(1) || CameraOffset <= 0.1f || ShiftLockOn)
{
yaw += Input.GetAxis("Mouse X") * sensitivity;
pitch = Mathf.Clamp(pitch - Input.GetAxis("Mouse Y") * sensitivity, -80, 80);
yaw%=360;
pitch%=360;
}
}
I'll be turning my camera in game and for some reason it just skips to some random rotation value
So move the if above all of it?
Transform target = (CameraOffset <= 0.1f) ? Neck : Character;
this is probably part of why it "snaps"
Cause of the switching?
it should be in Update not late update and the top lines
I changed the top line to neck
what difference would that make
input capture should be in Update no?
oh ok then
though, i don't think it's been stated what message this method is called from?
Here
yeah you didn't say what message this method is called from
could still be an issue if it's in FixedUpdate, but in that case the issue would be that the entire thing is in fixedupdate
I think I saw earlier mentioned "LatestUpdate" idk if they meant LateUpdate
I think that pivot switch is what might be causing it too look "twitching" though
Yeah late
similar for OffsetFix as well
So Should I use the neck of the character?
It seems the issue was the pivots changing
Now to make a raycast thing so camera can't clip through walls
I have 1 question and that is how to fix this error in the code. Otherwise I am a beginner and I want to learn how to make games in unity.
hover the green underline
flappybird yeah
Hey guys, I ran into this error I was wondering if anyone knows how to resolve it.
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
Thank you, I'll try this
after you need config your IDE
What's that 👀 😅
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
🎉 It worked.
Hi o/
I'm looking for a way to pause my charakter from moving/stopping the player from giving any movement imput while there's a pop up (like a journal). I can remember that there was some way I can make this work but can't remember 🫠
you could check for that state yourself, you could disable the input action/map/asset, there's quite a few ways
Oh neat there's a way i can disable any input action from the new input system?
I'll look that up cheers
I disable the "Player" action map while a menu is open
make sure it gets turned back on, of course 🙂
i put all of that logic into a single controller that decides things like "are we in a menu right now?"
That's actually Smart. My first thought was putting that in the movement script, because obviously we're handling movement here. But I'll probably be referencing a lot, since there's multiple situations in which the player will not be able to mvoe
Thank you 
Ok am I stupid?
https://paste.ofcode.org/cCsr6gXMhN4GbrerBxWZZ9
https://paste.ofcode.org/NH2WLPGc5v3jbNcDHFNzKw
How am I getting an null ref here?
The InputActionAsset is my InputsMap. I tried it with PlayerInput() before and another null ref, even though I linked it in the Editor? 🤔
I am stupid. I made the checkState private, meaning I wasn't able to access the information from the skript 🤦♂️
That would give a clear compile error
Sorry I have to ask again.
I'm currently setting up a Collectables and a CollectionTracker.
In the Collectables I have the Interaction logic, where I want to increase the amount in the CollectionTracker by the Amount of x which is part of an SO (e.g. I have Scriptable Object Nails set to 2, so I want to add 2 to the current amount of Nails). I know how to reference a value from another script if it's only one object, but how would I do that, if I have multiple of those?
My thought was to create a list of GameObjects which contain the script "Collectables" and then access the Component/Script through the awake method. But I'm not sure if that is the correct approach and idk how to do that 😅
Collection Tracker: https://paste.ofcode.org/bsfhzaBCfuee2wHSYKxzQa
Collectables: https://paste.ofcode.org/E9cSHZzEgCXkwmHCJ6PLiZ
SO: https://paste.ofcode.org/K9pAUVw4ajLafdAVnem2ZP
Perhaps you're wanting a collection of CollectableInteraction?cs private void Awake() { collectableInteractions = new List<CollectableInteraction>(collectables.Count); foreach(var collectable in collectables) collectableInteractions.Add(collectable.GetComponent<CollectableInteraction>()); }
I'm making a build system but for some reason it keeps auto deleting the cloned object when its parented to my workspace object
You should post code using the code guidelines
!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.
Does [SerializeReference] show the interface(reference object of it) in the inspector, right?
You can’t serialize interfaces if that’s your question
afaik, you can, they just aren't shown in the built-in inspector
i am trying to setup a currency system in my tower defense game. when ducks are killed, i want the blood text value to increase by 10. Said currency manager script is this:-
using UnityEngine;
using UnityEngine.UI;
public class CurrencyManager : MonoBehaviour
{
public Text HP;
public Text Blood;
int hp = 0;
int blood = 0;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
HP.text = hp.ToString();
Blood.text = blood.ToString();
}
// Update is called once per frame
public void SpillBlood()
{
blood += 10;
}
}
I am figuring out whether collisions are occuring or not and then changing the value of blood in CurrencyManager:
using UnityEngine;
public class CurrencyAdderOnCollision : MonoBehaviour
{
[SerializeField] CurrencyManager _currencyManager;
// Update is called once per frame
public void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Collision Detected.");
Debug.Log("Adding blood to pool.");
_currencyManager.SpillBlood();
}
}
it ends up giving me this error
Unity can serialize interfaces with SerializeReference, it just does not draw them in the inspector unless you get a package for that
You are accessing something that is null in Start, could be HP or Blood. Look at the line that the error points to
it's currently pointing to HP.text = hp.ToString();. Since I have already declared HP, if its field namedtext is NULL, then I am changing it to whatever hp.ToString(); is. Since hp = 0, that's not null either.
You have declared HP but that doesn't mean you have assigned a value to it
Look at the inspector of this script component
And if it's assigned then make sure you don't have extra CurrencyManagers in the scene
ok so HP and Blood are somehow appearing in the inspector. why though? isn't that only supposed to happen for stuff which have the [SerialisedField]'modifier?
Unity automatically serializes public fields
damn, i was away from unity for just a month or so and i forgot about this. btw, what can i do to fix the error? should i just do smth like HP = this.HP in void Awake() or something?
Unity needs to know which Text component you want to reference
So just assign it in the inspector?
If possible
I can't drag the Text component in the inspector, it doesn't allow me to do so
could you maybe explain to me what the person in this video did in this case?
apparently it's supposed to do the same thing but, he was somehow able to do it in the code itself
he created an instance variable(like a constructor i am assuming), then assigned this gameobject to the instance variable in Awake() and then reffered to this instance in the other script and used the function AddPoint()?
Nothing here actually assigns a value to scoreText or highscoreText, so they must've done it in the inspector too
It could be done with GetComponent via code, though.
pretty sure they didn't do smth like that...
Master Unity UI! Start here ➡️ https://cococode.net/courses/master-unity-ui?utm_source=youtube&utm_medium=video&utm_campaign=25
Let's create a simple points scoring system in Unity game! I'll also show you how to add a high score counter and display all of that using simple Unity system. That way you will be able to create a similar system ...
last question, i am seeing that the guy did not have to use the update() method at all, on the other hand, if i do that with my code, it doesn't rly update it. only when i copypasta whatever is present in the start block in the update block, does it actually happen.
oh wait, nvm, i figured it out, the function itself changes it, mb
Update is just a method that unity automatically calls every frame for your monobehaviour script
Hello all. I've been trying to set up Playmode tests.
Currently I have EditMode tests set up in Assets/Tests/Editor and Unity is able to find them. I didn't have to create an assembly definition file for this. And in this Editor folder, I'm able to reference code from my actual game folder (for example the public code in Assets/Scripts).
I have tried to create Playmode tests but it seems that it's not as easy as just creating a Playmode folder. I opened the Test Runner instead, went to Playmode, and create a new folder inside Assets/Tests for the playmode tests. It created the assembly definition file there, but I'm not able to figure out how to make it reference the code in Assets/Scripts.
This is all the information I think I have right now. Although, I'd appreciate if someone could help me ask the right questions, and also help me sort this issue out.
Thanks in advance 🙏🏻
And I'm not really sure if this help request is fit for this channel 👍🏻
Does your Assets/Scripts have an asmdef file so you can reference it in your playtest asmdef file?
I don't remember adding one myself, and one doesn't show up when I search.
Good reminder though, because I did try adding it before while I was attempting to set up Playmode tests. When I added it, I got a million (exaggerated) compiler errors because most of my other code broke.
Actually it shows the interface(I mean the fact that it is in List).
Yes I also meant to use it for List.
Yeah they're just not editable is what I mean
You need to implement the unity stuff then in your asmdef file, if you create one. Otherwise it will be a decoupled script folder that does not know about monobehaviour and what not
I'm not sure what you're referring in "Unity stuff". Are these my external dependencies and packages? Or the code in Scripts? Also, how is Unity able to find the classes right now in Editmode?
As you do not have any asmdef in your Assets folder, everything has access to all Unity namespaces. But if you add an asmdef file to a folder, it will separate it entirely from Unity and you have to edit the asmdef file to include Unity stuff, for example like this:
I am not entirely sure, what errors you got, but they should show you, what namespaces are missing
i see. so I will have to manage these deps myself. Well, thanku 🙏🏻
@rich adder sorry for late reply (:
It is literally telling you what to do 😉
What do you expect that to do
Is there a way I can automatically make this scroll area scale vertically without changing the canvas scaler's settings?
I've already done the rest of the UI with a specific setup so it'd be pretty difficult to change everything else for this one element, is there another way?
i'm watching tutorial how to create flappy bird game and this will this will make it so that when you press the spacebar it puts you a little higher than you were before
Why did you do that instead of what the error said to do
idk what i need to do
The message told you exactly what to do
you should go trough the unity learn tutorials probably, rather than using some maybe bad or outdated youtube tutorial. You clearly are missing basic level knowledge of coding. So either try the unity tutorials OR take some super simple c# tutorials to start with.
To be fair this change happened like two months ago, most tutorials will be out of date. Thankfully the message in the IDE just says exactly what to replace it with so it's a super simple fix
do you know any simple tutorials?
btw it's this correct now?
or?
no
No. That’s far from correct.
yeh, thats true about the change on linearVelocity. I was talking about not knowing, how to assign a value to something. I do not see this ending well with the missing knowledge. But maybe I am overrating the situation
realy
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks
Wasn’t it actually velocity originally but it got deprecated and recently removed?
Or maybe i’m remembering that wrong.
Which is why you have to do that
it still doesn't work
#💻┃code-beginner message go back to this
and then do what it tells you to
And then stop and go to some basic tutorials about c# please
Hey everyone, where can I get help on the Unity courses from Unity Learn? I'm doing the Junior Programmer course and I keep having an issue importing the asset packages, seem textures are not applied to the assets everythign is Pink. I am following the 6.3 LTS version but for Prototype 2 I resolved the issue by importing into 6.0 LTS and converting to 6.3, but this is not working for Prototype 3 assets. Anyone know how to resolve or how I could correct manually?
sorry bro
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Read the error message. It's very clear about what to do. It's literally just plain text instructions. Actually try to interpret the words in front of you instead of smooshing your keyboard and hoping it works.
thanks anyway
Programming isn't magic. Words mean things like they do in any context
You can just read the messages and they say what to do
All good. It was not meant offensive or whatever, but clearly saying whats missing helps you more than "spoonfeeding" you knoweldge you need every day when developing 🙂 https://learn.unity.com/course/beginner-scripting
Learn about programming for game development, from the very beginning with these easy to follow video tutorials.
it's ok thanks
You become what you eat afterall. If you get spoon fed, you’ll become a spoon. And a spoon can’t program.
What a brilliant line, love it.
You know, that succinctly summarizes something I have struggled to convey to people for years.
I'm gonna yoink that for my metaphor toolbox
Discussable if you get fed with or by a spoon tho 😄
If it helps you convey what you're feeling towards people then go for it.
Yeah, you get fed with a spoon, you're fed with spoons.
spoons fed you.
I take full respoonsibility. I'm sorry for this.
And who gives a fork about teaching spoons 😅
forking nobody, thats who
Hi everyone, I'm a beginner Unity developer and now I'm working on a small iOS project. This game is about "chasing" falling musical notes. I have 2 gamemodes
- In Main menu hit Play - random song and random instrument - play
- In Concert hall - select an instrument - choose a specific songs for that instrument - play
I have a list of songs that appears for being chosen and a list for random songs that I don't want to appear anywhere just to be there to load random songs when button Play is pressed. I don't know what I'm doing wrong, but I can't implement this. If anyone here can help I will share the github link to see the code and to understand exactly what's in there. Thanks
you will definitely need to share the code and explain exactly which part you're having trouble with
as well as what if any debugging steps you've taken and their results
Hey guys, I've just started with Unity - I am programmer, so in this way It is fine, but what I am a bit confused is a documentation. For example - I want to create a game menu, just some simple one and test the capabilities, but when I dug into the official documentation there is nothing. Woirking with UI Builder is simple as well as styling, but what I did not find is the handling the UIDocument with code. I have found a lot of videos how toi create menu, but I want to follow official docs. Why there is nothing, or am I blind? Can you help me to find some good material how to handle / create a simple game menu like - working with windows, quit the app etc? Thank you!
Sure, here are all the scripts https://github.com/KornyIsDeveloping/RubatoNotes/tree/main/RubatoNotes/Assets/Scripts
if you're referring to script reference, that's a reference, it's like a dictionary. you wouldn't learn a langauge just with a dictionary
try looking for guides or tutorials
For the debuggings steps, I tryed a lot of things from the internet/chat gpt, but all that I've got from there were bugs and errors and the random songs playing for both gamemodes...and each instrument playing only one song from its defined songs.
Yes and this is very strange. It's no problem to search for othger tutorials / videos. I just want to find some official data how to handle Unity basics for UIBuilder topics, for example, if I create a buttons, what are the methods for events etc.
learn.unity.com has the official tutorials for using the methods and components in practice
Hey guys im working on gamepad support and trying to implement my gamepad to work like a cursor. But, for some weird reason my virtual mouse doesn't point at ui (can't highlight) and clicking doesnt seem to work. This is the code im using:
private void UpdateMotion()
{
if (virtualMouse == null || Gamepad.current == null) return;
Vector2 stickValue = inputs[0].action.ReadValue<Vector2>();
stickValue *= cursorSpeed * Time.unscaledDeltaTime;
Vector2 currentPosition = virtualMouse.position.ReadValue();
Vector2 newPosition = currentPosition + stickValue;
newPosition.x = Mathf.Clamp(newPosition.x, 0F, Screen.width - padding);
newPosition.y = Mathf.Clamp(newPosition.y, 0F, Screen.height - padding);
InputState.Change(virtualMouse.position, newPosition);
InputState.Change(virtualMouse.delta, stickValue);
bool isPressed = inputs[1].action.triggered;
if (previousMouseState != isPressed)
{
virtualMouse.CopyState(out MouseState state);
state.WithButton(MouseButton.Left, isPressed);
InputState.Change(virtualMouse, state);
previousMouseState = isPressed;
}
AnchorCursor(newPosition);
}
While in my inputactionasset i've tried to set point to the position of the virtual mouse and for clicks to be on the virtual mouse left button and also the gamepad button. Im really not sure why it wont work. The event system is also set up with my custom ui input module.
Doesn't the VirtualMouseInput component handle all this automatically?
And what do you mean by "custom UI input module"?
I mean I set this up to my own ui inputs
Haven't heard about it
Any ideas?
would be far easier if you shared the scripts related to your issues
what exactly is your question? also please share specifically the scripts that are relevant to your question rather than dumping the entire project
rather than your whole github repository
I would like to do that but I tryed a lot of things and it's a mess in there even I don't know what are those scripts supposed to do.....
you wrote the scripts..?
is adding/removing components to game object at runtime considered bad practice or bad for performance?
even if its writtne by AI its your job to understand what is being done and how
then try your luck with the ai
explain why and how
but nobody is here to fix and clean up ai code for you
good chance its prolly fine, a big downside of doing so is you can not make references via the inspector
has some overhead but unless you are doing it many times a frame sure its fine
If it would work...I wouldn't request help here
"but nobody is here to fix and clean up ai code for you"
as stated
Ok I don't udnerstand anything.......
Not to be rude. But i really wouldn’t recommend using ai.
No proper structure, no code.
using it will not help you actually learn things
all it will do is toss you in the deep end before you can swim
so i have a base class called BossAttack, and another called BossBrain
each bossAttack has public variables that allows u to modify like how much damage u wanna apply, how fast, how often it happens...etc
and then bossbrain searches how many BossAttack exist on boss GameObject and execute them one by one
so when boss goes to phase 2, i remove one of those attacks
add another new ones
and make the ones left deal more damage and happen more often
the reason i went with this approach, is because i was able to modify values in the inspector so it's better for design
and now i can kinda create new bosses or make some bosses interchangable as long as they have the animations required for each attack i add
its one thing to use ai, whatever, but its a completely different thing to rely on it so much you have no clue whats actually being done in your own project
youre actively hurting yourself in the long run.
so what part are you adding and removing at runtime?
Ok so no one can help me here...even if I used ai
It's more like no one wants to help somebody that's using ai.
a new instance of BossAttack
i have multiple classes that inheirt this class and have different implementation
ok and when is this happneing, i am trying to understand how frequenet it is
when boss changes phase
when it reaches 50% hp, i remove some instances and add new ones
that's it
it's not like happening often or in Update
yeah you are totally fine then
It's a built in component that does all the stuff you seem to be programming yourself
Right ive tried it and it doesnt work the way I need it to and I'm still having the same issue with it not detecting my ui
Im really not sure what it is due to
I've set up point, a custom control scheme with the virtual mouse but it just won't detect ui
Here is my full code
Is there a reason you used a custom input actions asset for your input module?
i need help making a knife like people playground that stbs into objects and can be pushed in and can only be pulled out the opposite way it was pushed in
im making a combat game ive got every other weapon but stabbing tools
help with that specifically
i dont know where to start
well you start off by breaking your problem down
ive got the knife sprite with a rb2d and a collider (it is 2d game)
first find the mvp of your concept
then break that down into its basic individual challenges
thats step one
ive got the knife to drag eith the cursor in a 2d space so first i need the knife to stick into a 2d square with a rigidbody
Found a tutorial and followed it, did not know about the virtual mouse. After trying it, ive noticed it doesnt support changing between normal mouse and controller so decided to stick with it. In my case however, I cannot interact with the ui. Im unsure why
There's almost certainly no good reason to be using a custom asset for the input module and it may in fact be the cause of your problem
i would try:
- The default actions asset in the input module
- Using the built in virtual mouse
Ive tried it but still nothing.
Clicking only seems to work when the ui is selected but highlighting never works
For both custom and unity's solution
is it that performance heavy to frequently pass structs with many variables stored in it?
"that performance heavy" is a vague question
"many variables" is also very vague
it's more work the more copies and the more variables you have, multiplicatively, but it's a few instructions worth
unless you have millions of copies and thousands of fields, it's not going to matter. there will be other things much slower
hey so like just to sanity check myself rq, onStart() only gets called at the very start when the project opens as soon as the script is enabled right?
and onEnable just comes after that?
OnEnable is when it becomes enabled & active
Start is the first frame it's enabled & active
is something not as you expected or why the question
Awake to init self, Start to access other things post init
if i have a physics-based player, should i run the movement in fixedupdate or update?
"run the movement" is really vague
what does transform.translate mean 0-0
Generally you do things that interact with the physics engine in FixedUpdate
It means apply a translation to the Transform
Which is a fancy word for "move it"
and transform is its position?
No
The Transform is the component responsible for the object's position, orientation, scale and parent/child relationships in the scene
ohhh alr i get it now, ty!
last weird/short question: how could i move a rigidbody at a constant velocity while updating it in fixedupdate AND update?
Hey uh, I need help making a script that is basically able to exactly copy maya's orient constraint. I'm making a physics based game and I'm trying to animate my character with a custom rig in-engine. to do this I need to be able to mimic maya's orient constraints and my attempts so far have been really dire.
The character I'm making is a physics based mechanical android and part of their design includes hinge/gimbal joints, which are nested joints for different axies. (think that's the plural of axis) For some reason Euler doesn't like this and while I understand code somewhat I'm very much artist brained and find it extremely difficult so if anyone does try to help sorry if I'm not totally a whiz.
In this gif hopefully you can see my shoddy attempt in unity, and how the maya version using the native animation constraints works perfectly.
If this isn't the right channel to discuss this please redirect me!
What are you using rn to "copy" the rotation?
this is my current script...it's...bad...
AI assisted because I suck at coding
er well firstly if the rigs are the same then you could directly copy local rotation over
You want to avoid working directly with euler angles
and also the fact there's nested joints. apparently unity's parent system doesn't like that but they're essential for the design
noted!
you are working with local rotation so that doesnt matter. Local position and rotation is directly relative to its parent
Id try to just use rotate towards and use the local rotation quaternion as is
The 'bones' animation type rig I made and all the individual meshes of my character are all zeroed out so they should all have the same local orient
this is a script attached to an object, when I move my mouse its position changes, but i cant see it.
any reason why?
Mouse position is in screen space so this wont work
thank you! I'll try to analyse this.
If you can't see it how do you know that it's position is changing
because on the objects inspector its showing a changing position
So, the numbers are changing but the object is not visibly changing position?
yah
Or is it moving just fine but not where you expect it to be?
why make it complicated? i gave the answer
i thinks its something with camera position not being converted to world position or something
ima figure it out
Yes, that's definitely the problem, but if the object isn't moving visibly at all there's more than one problem
🤷♂️
If 2D you need to correct the position z yourself so its not outside the camera clipping plane
Hey! so that rotate towards advice has helped, it seems a lot smoother. and I don't think I see any massive flips? But the joint's later down the heirarchy do seem to be acting strangely...Like a sentient IK controller with a crack addiction.
If you only use quaternions to rotate it should be okay. Euler angles experience gimble lock which causes fuckery like that.
Ideally we only use euler angles to make a quaternion and then we * our quaternion to rotate another.
Share code again on a sharing site
!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.
can anyone help me with my game
i am trying to make it generate
send me a friend req if you can help
!ask 👇
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
ok
sorry if this is a dumb question, but this has been making me go insane for the past 30 minutes now
i'm trying to set up some world space things that the player can click on to interact with (the mouse is unlocked in the section)
i check for the custom worldspace button component with a raycast, that uses the mouse position, and gets a ray through the main cam (i specifically added a layer just for these, to make sure nothing can be blocking the collider)
[SerializeField] LayerMask wsbLayer;
Camera cam;
void Start(){
cam = Camera.main;
}
void Update(){
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 100, Color.blue);
if(Physics.Raycast(ray, out RaycastHit hit, 100, wsbLayer)){
if(hit.collider.gameObject.TryGetComponent<WorldspaceButton>(out WorldspaceButton wsb)){
if(Input.GetMouseButtonDown(0)){
wsb.onClick.Invoke();
}
}
}
}
if i put this on a random cube in the world, it works
however, if i put it on a collider that is in front of the camera, and is positioned where i want the interaction area to be, it just refuses to work
i have the layer set correctly, i have the component on the object, i tried logging just about everything, and when debugging the ray, it shows up correctly intersecting the object, and i even tried moving the collider farther from the camera and scaling it up
what could possibly cause this? cus i am completely lost
Id say double check the layer mask. Make sure its a 3d collider. It is a weird choice also to keep raycasting and then check for a mouse button click
Normally we would wait for input and THEN raycast to look for the target
Another solution would be to use the event system pointer events instead if this custom solution
collider and layer are def correct, i triple checked them
also the input is like that for a reason, since i also want to handle on hover events later on, for animation purposes
Gotcha. Debug to check if the raycast hits something first as that would be the only other thing I can think of rn
What is the collder you want to hit btw? box?
Definitely use the event system interfaces then because it will be super easy to handle hover, click, drag, etc without custom logic
I even have an example project!
https://github.com/rob5300/Unity-EventSystem-Events-Example/
i want only the smoke to be visible and not the squares...i have seen people somehow make the squares transparent
Are you referring to the white and gray squares? Because if those are visible that means your image isn't actually transparent
google images moment
i imported the img from google
Yeah so you got a fake transparent image.
wait, so it won't work?
yup, regular boxcollider
also i already tried logging basically everything, but i went trough it all again in case i messed up the first time (with the layer being passed, nothing is hit; without the layer, it skips through the collider, and logs the name of the object behind it, which is the building you can see in the screenshot)
gonna give the event system interfaces a try also ty for the example repo, super helpful :3
some silly thing must be wrong then such as a disabled collider component
Correct. It's not actually transparent so those won't be transparent.
Also it is a really bad idea to just grab stuff from Google images unless you don't plan to ever release it
lol, this game will just be in my repo
i have photoshop so...
If it's public then it's still a bad idea. You don't have the license to use that image
now i need to make my own effect too? oh poop
google is usually filled with fake pngs (plus as others have mentioned it's usually copyrighted)
try https://opengameart.org/ it has tons of good stuff that is all cc0 or attrib licensed
weirdest part is, that it's not that
if i drag it outside the camera, and i hover over it, it hits it, and it works just fine
Realistically it wouldn't be that difficult, cloud brush in photoshop (or whatever it may be in there) without full transparency, and make it white then you can reuse it for different colored effects in unity by applying a tint
Apparently using StopCoroutine to manually stop a coroutine from executing causes a "Coroutine continue failure". I'm told that it's harmless and, at least from my testing, doesn't seem to be hurting anything, but it's annoying seeing it in my console. How do I get rid of this?
thx, i got it to work, although it's not as disgusting to look at...
I know that, no worries :)
I am not understanding how it becomes null...
Maybe the best solution was not to sending here...
Time to disable everything and re enable one by one to find the cause!
wait, is it a bad idea to have unity and photoshop open at the same time?
So if you know how to troubleshoot a null reference exception, then which object on the offending line is null
If your PC can handle both why is it a bad idea 🤔
too bad its a potato, 3rd gen i3 with no gpu
Ok so you answered your own question
How can I make a functional GroundCheck? One that detects when objects touch the ground (I need to know how to do this to create a jump button).
What did you find when you googled it?
I think I found it, sorry
Is there a place where I can find official information about public class states?
for like state machines
In the docs.
What class exactly are you looking at?
YO
anyone know gitlab and know how to stop it from asking me every 2 minutes for authentification when having forked open
or push, imma flip tf out rn
i think that's really an issue with fork honestly, it did the same to me for github. authenticate with a token and it should stop
Is it better to put raycasting for character collisioning in fixed update or update?
unless you're calling Physics(2D).SyncTransforms every update, then your colliders are only ever updated on physics frames (same cadence as FixedUpdate), so it makes little difference in precision, and whether it makes a difference for performance would really need to be profiled but unless you're doing a lot of checks per frame then it makes little performance difference
I'm making a custom raycast character controller
yeah i figured. what i said still applies
just keep in mind that if that object has a collider but no rigidbody then its collider being recreated every FixedUpdate (on account of it not being moved via rigidbody) will likely be more performance costly than a few raycasts each frame
I don't have any collider on the player
It's using raycasts that fire at parts in the scene
how could i "visualize" whats happening when i do math counts in c#? like, I needed a "fov" raycast based, there was a bunch of calculations that I couldnt comprehend why it was working ingame as I wanted
Debug.DrawLine(Vector3 start, Vector3 end, Color color, float duration = 0.0f, bool depthTest = true);
Can use to visualize raycasts
or use the physics debugger if they are 3d raycasts
i have an enemy collision script which is used for single target units. do i need to make a diff script for one which does an aoe attack?
Not necessarily.
There are no absolute answers through, it really depends on the details of your game and the desired enemy behavior
for single target units, what i am doing is that the tower gives information to the bullets, but, for aoe units, they don't require a bullet, since the particle system does collisions
i would personally use different components for each attack, but have them either inherit the same base class or implement a specific interface, then you can compose your enemies however you want mixing and matching any attacks as you see fit
oh...so the same script has two options, both single target and multi target attacks in it, and i can choose which one i want to use
i mean the attack itself is its own component and you put whatever one(s) you desire on the enemy so it uses the one it has assigned
i think you got something mixed up, it's not the enemies who can attack, only my units.
it's a tower def game
okay so then substitute the word "enemy" in that sentence for "unit" or whatever the fuck you want because that part isn't what is important
should i add an if else condition to check whether the unit this script is being attached to uses a single target attack or a aoe attack and then those different blocks of if and else handle single target and aoe attack respectively
no, make the attack component worry about its targeting
the "unit" or the overall controller for that object should just care about referencing the attack component and calling whatever targeting/attack methods are required (which would be dictated by the base class or interface that i mentioned before)
tehre are many, many ways to do this
And there are many good ways to do it that don't involve repeating a bunch of code that is shared.
Hey guys got a question. I am using Fishnet for my multiplayer solution (this is not a fishnet question though). I have a class, named ItemInventoryMember. I am making this a SyncVar (fishnets synchronized field) in another class.
The issue is that in my ItemInventoryMember class, I have public properties such as
/// <summary>
/// Gets the quantity of item occupying this <see cref="ItemInventoryMember"/>.
/// </summary>
public int Quantity
{
get { return _quantity; }
private set
{
if (_quantity != value)
{
_quantity = value;
}
}
}
The fact that this has a private setter causes fishnet to have trouble serializing them for networking. Basically, i need to make these public setters (ie just use set) for it to work. I don't want other scripts to be able to access the setters though. Any thoughts on how I can approach?
the property itself shouldn't be serialized at all, it should be the _quantity field that is serialized. the property is really just a get and set method, so if fishnet is attempting to serialize that directly then it's a bug in that package's code that should be reported
or if you are decorating it with some attribute that makes it sync then you're doing it wrong, you'd need to sync the field not the propery
I didnt write anything custom, just using Fishnet out of the box. The docs say SyncVars are used to synchronize a single field. Your field can be virtually anything: a value type, struct, or class. To utilize a SyncVar you must implement your type as a SyncVar class
where i just have
private readonly SyncVar<ItemInventoryMember> _pickupableMember = new SyncVar<ItemInventoryMember>();
then, again, it shouldn't be trying to serialize the property at all, and just serializing the _quantity field. presumably fishnet has its own discord server you can ask for further help in to make sure you are doing things correctly
and you should actually let them know what (if any) errors you are getting
Yeah I've asked about it just waiting for a response. Assuming this is intentional on their end, is there a way to make these properties not accessible from other scripts without making them private?
your property is already correct. again, the property itself shouldn't be serialized. the backing field should be. if fishnet is attempting to serialize the actual property rather than the field then it's a bug in their code.
The docs are pretty clear here:
https://fish-networking.gitbook.io/docs/guides/features/data-serialization
if you would like to exclude such fields from being serialized use [ExcludeSerialization] above the field.
You should simply serialize the field and put [ExcludeSerialization] on the property
so it doesn't attempt to serialize the property
the field would need to be public though
alternatively you can write a custom serializer
is its serialization really so naive that it doesn't account for full property vs auto property?
seems that way.
that seems like a huge oversight
So i guess its a little pointless to even use the ExcludeSerialization if i have to make my backing fields public anyways ... lol
as in the whole point is so other code can't touch these. seems like exposing the private backing field as public is even worse because it can now be altered + would bypass any logic i was using in the property at the same time
I mean i just think the fact it tries to serialize a public setter by default is stupid
maybe this will work?
It's not mentioned in the docs
(to serialize a private field)
hey I need help with my spring joint, I'm getting this error:
Skipped updating the transform of this Rigidbody, because at least one of the position vector's components is infinite. Could you have applied infinite forces, acceleration or set a huge velocity?
it only happens when my grappling hook hits something and pulls the player into another collider
as soon as the player touches the collider the forces go to infinity
you're probably entering some degenerate state where a divide by zero is happening
are you doing anything like moving the objects directly in your code instead of using forces etc
yes, I'm using MoveTowards to recall the grappling hook, let me see if it stops the error if I comment that out
yes that was almost certainly it
but now I'm not sure how to make the grappling hook return
MoveTowards is just a mathematical funciton, it doesn't actually move any objects
you're assigning the Transform position directly or something like that
if (state == "returning")
{
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
sj.maxDistance = Vector3.Distance(transform.position, player.position);
transform.position = Vector3.MoveTowards(transform.position, new Vector3(player.TransformPoint(hand_position).x,
player.TransformPoint(hand_position).y),
transform.position.z);```
I've been setting the spring joint max distance to "turn it off"
since there's no way to enable/disable spring joints
I suspect the position setting wouldn't be a problem if the spring joint was off
but I don't know how to do that
unfortunately the way to disable a joint is to destroy it
Didnt work unfortunately, thanks tho
Hey everyone, I'm stuck in a Terrain Data loop. I duplicated my Terrain Data asset (DesertTerrain -> GrassTerrain) to use in a new scene. I assigned GrassTerrain to the Terrain Collider, but the main Terrain component is still stuck on the old DesertTerrain data. Clicking 'Assign' just forces my Collider back to the old Desert data. How do I force the visual Terrain component to switch to the new asset without it reverting?
In short what I'm trying to achieve is duplicate Terrain A, which would result in having Terrain A and Terrain B, and only change Texture/Material on Terrain B.
Sorry for wrong channel, will do
@slender nymph is this similar to the solution you guys were suggesting?
I'm honestly quite confused by Quaternion.Slerp atm. To give more context I'm trying to create a situation where a transform smoothly rotates -45 degrees in the Y axis, only once everytime a string is the same.
Right now the behavior seems to only have like one frame of the slerp doing anything or maybe its not doing anything at all, in testing there is a very rough estimate of ~0.01 change in rotation for all values.
I have tried quite a few things, the rotation its-self works without slerp, I'm a java programmer learning c# so I assumed the problem was that I needed to clone each variable, but this was not the case, I've also tried some other configurations to no avail. I have also searched my problem online and I did not see anyone with the same problem as me.
If anyone could help me resolve why my slerp isn't doing anything that'd be amazing 😅
Quaternion oldLowArmRot = lowArm.rotation;
if (dir.x < -15 && dir.y < 0)
{
if (orientation != "uR")
{
lowArm.Rotate(new Vector3(0, -45, 0));
lowArm.rotation = Quaternion.Slerp(oldLowArmRot, lowArm.rotation, Time.deltaTime * 14);
orientation = "uR";
}
Have you tried working with AI? Usually it's sufficient for problems like these
I am quite against AI, but yes I did sadly ask it about this problem, and it came up with some hallucinated solutions that didn't work, or were to stupid to try 😛
Which one were u using? I can recommend one I use and it's pretty good, definitely faster than searching things online, at least for simple problems
I only ever ask AI about what to search for, not the whole thing.
not exactly. i was simply suggesting a basic form of composition
something like this
and i got this as an answer
ain't no way i am using this things code though
If you're only calling slerp on one frame then of course it will only do one frame worth
Also I have no idea what that sentence about being a Java dev and "cloning" each variable means
Ah, that would make sense then lol, I'm going to have to rethink how Im structuring it at the moment since this is the case
'preciate it, i'll be back if it some reason doesn't work though
Maybe you're thinking of a coroutine or a tween framework?
apparently what i described before is a version of the strategy pattern and how it is typically implemented with components in unity. so yes, @tired python that is what i meant
Applying lerp so that it produces smooth, imperfect movement towards a target value.
@rich adder Not sure what the emojis are for. If the AI suggestion isn't a fit for the problem, feel free to explain why, otherwise it's just childish.
we dont suggest ai around here as it's pretty bad at helping people
too much to even get into right now, this topic has been beaten to death. Recommending someone to "just use AI" is lazy and goes against the scope of this server..
I wasn't only recommending it, I was offering to choose the right one, and see what can be done. It wasn't "just use AI" and ignore the problem...
"use the right one"
"you just have to give it the proper context"
"get better at prompting to get good results"
yada yada
"just know what your trying to learn so you know when it lies to you" 😛
I see you're unable to have an adult conversation, farewell
just a heads up that most of the server feels this way
we've all heard all the lame promotions for AI already. you can proselytize elsewhere.
Didn't know it hurts your ego so much
just take a hike and stop being a bozo
upto folks whether or not they want to use AI, but saying that someone's personal choice not to want to use it is childish is strange imho
I said the response was childish, not the perosnal choice
joined the server today, probably knows nothing about unity here to just try to rage bait
Before this turns into the usual conversation, let's make a thread.
Otherwise, we can move on from the same responses we all have heard many times before.
Sorry, we're not playing "get the last word in". Thanks.
holy 💩
If you want to debate AI, please make a thread.
You can opt to use a coroutine if the control flow only encounters this situation in one frame but you are wanting it to operate through multiple frames therafter:```cs
if (dir.x < -15 && dir.y < 0)
{
if(!finished)
return;
if (orientation != "uR")
{
StartCoroutine(LowArmRotate());
orientation = "uR";
}
}
private IEnumerator LowArmRotate(float duration = 1f)
{
finished = false;
var initial = lowArm.rotation;
var target = ...;//todo
for(int progress = 0; progress < 1f; progress += Time.deltaTime/duration)
{
lowArm.rotation = Quaternion.Slerp(initial, target, progress);
yield return null;
}
lowArm.rotation = target;
finished = true;
}```
how do i search for other components attached to a gameobject without using something like GameObjectToSpawn.transform.GetChild(0).GetComponent<EnemyCollision>();
the value of the position sometimes ends up making me redo a part of the code everytime i add something new
I don't want to use find either cus it searches through all the gameobjects present in the hierarchy which is costly
wait, i don't want to use the slide thingy
what does that mean
u know what, i am a moron, ofc that would work
as in, use my mouse to put the component into the serialised field
ah, well unless you want to do annoying Find or GetComponentInChildren calls, a serialized field on a root component is the best idea
there's no better way right?
the way i suggested is the best way
cus the get component in children thing is srsly gone case scenario
why don't they just remove these stuff...
oh...cus projects which are using them won't work anymore
GetComponentInChildren usage can be appropriate sometimes
oh...sry i was referring to GameObjectToSpawn.transform.GetChild(0).GetComponent<EnemyCollision>(); not GetComponentInChildren . tbh, the later does seem more useful
void OnParticleCollision(GameObject other)
{
Debug.Log("Particle Collision Detected.");
Destroy(other);
}
I want the gameobject which is colliding with the particle to be destroyed, not the gameobject the particle system is attached to
how do i achieve that?
one way would be to just place this code onto the gameobject which is colliding with the particle, but i don't want it to be managed by that gameobject. I want it to be managed by the unit which the particle system is attached to
I thought other would already refer to the other gameobject that you hit?
Does the particle system have a collider and is hitting itself or something?
i don't think so...?
it's just one particle tbh, which is growing in size overtime
You also gotta consider which one takes more process. For instance GetChild(0) sounds faster then GetComponentInChildren.
Of course this doesn’t matter if it’s only running on one instance.
Not really tbh, getchild(0) is super assumey and flimsey which isn’t worth the potential cost there imo
if process time mattered you’d do things in a way where you wouldn’t need to do this period
What is this server about
A game engine
literally lmao
just learn before you learn with AI bro trust me
Correct me if im wrong but using a singleton would be a lot better for this right?
Singleton would be for one and only one instance. Thats not the case I assume with the EnemyCollision being a component on several enemies (I assume). So a direct reference on the root object that has been spawned might be the better approach
Oh i didnt see that XD, thanks for the info tho
yes, learn in a traditional way until you have some sense of when the AI could be halucinating and you research further, you dont need to know any topic 100% but you will quickly get a sense of how things work and that will make you able to spot when the AI is being funky
how optimized actually are raycasts?
can i just run a bunch every frame or on FixedUpdate without much fps loss?
Very optimised
do not worry about raycasts
What even would be the alternative if someone said they weren't. Use the things the engine provides.
alright thx
yeah ik im just wondering how many i can use if more is better
i can use something different but easier with raycasts so gonna go with them
I suspect some people might see 'raycast', get mixed up with 'raytracing' and worry about efficiency but they're really not on the same level
It's more than beginners forget computers can do lots of things, fast. It's hard to imagine in our brains such large calculations so naturally the assumption is that it will cause "the lag"
You see the same questions in other things like "too many if statements" or "are loops going to lag"
Hundreds if not thousands
Tens of thousands also chilling tbh
Ya I did 70k one time and you can see it a bit in profiler but definitely not as much as rendering / meshes do
It was at the 500k-ish where i needed to ideally move to the raycastcommand shit
They really optimized the shit out of raycasting huh
I think this should go into something like #💻┃unity-talk , as its just about personal experience in the overall scope of projects, neither code nor unity related specifically. Also talking about AI is happening over there anyways and has been discussed to extent already
Okay ill move it over, sorry about that
damn bro how is it so good
In rendering I have fog on. Is there a way to disable it in certain volumes? Or disable the fog in rendering and make fog as a volume? I have pretty big contrast between some rooms in my scene and I want to be able to control the atmosphere more
PhysX probably
You might need hdrp or a custom asset
HDRP specifically has that but of course it has a lot more too
Does anything else change with HDRP
I know it does change a lot but would it break my game using regular urp
A lot changes yeah
anything else besides what? The entire rendering, lighting, and shading model changes. That's a lot.
I've got an issue with "No Camera" flashing on my screen. To reproduce, I go into my AR scene which is required to have maincamera disabled so it can use XROrigin. I have a additive UI scene with a button on it. This UI scene is used on a lot of scenes. When I click the button it unloads all current scenes and then loads the new one async. On the next scene I have code that enable main camera in Awake(). I don't know how to get rid of that gap as I don't think I want the UI scene controlling cameras.
The XROrigin sould have a Camera you can use as MainCamera anyways. Any reason, why, on an XR setup you would have a non xr setup running?
AR is only small part of the game
Ah, got it.
Note that this only will show in the editor, not in a build
It will just be black?
Ok...that is no big deal. I'm thinking I can also have camera controller in the UI...maybe I dont' need to restrict that.
I'm going into an inventory page. I know I will always want main camera
you could also hook your main cam to the xr cams state. When it switches off, maincam switches on and vice versa with a simple event.
That sounds like an interesting idea...I already have the events setup
Is it not possible to manipulate a component if it's part of an array? Or is there something I'm missing?
I'm trying to animate an object by manually setting the SpriteRenderer.sprite in an array, and while debugging, it shows that the correct sprite has been assigned the SpriteRenderer component. However, in-game, it still shows the standard sprite.
I figured I'd ask here instead of the animation chat, since I don't use the animator component
https://puu.sh/KI7FR/74103512a5.png
You can change the sprite whenever/wherever you want. Being part of an array has no bearing on that.
That's what I was thinking too
Why it's not showing, could be any number of things. Possibly overridden elsewhere in your code to be the standard sprite? Could be you're looking at the wrong sprite? Could be that this component isn't on the sprite you're looking at?
Most likely you are looking at a reference to a different SpriteRenderer than you expect
For testing purposes, I only have that one object in the entire scene. At least the only object with a SpriteRenderer. I'm curious if it's even possible to have any SR components if it's not even attached to an object?
just fyi - the object itself has no notion of being in an array, nor of being referenced in general. references are a one way link (aside from gc/reference counting purposes)
this isn't specific to c#, just how references work
Check which SpriteRenderer it's referring to
how many elements in your array? Which element is this one?
Index 0. Only object in the array
Ok and check that it's actually the object in the scene, and not for example, a prefab reference
not normally, but an alternative could be that it's not in the scene - it could be destroyed or a prefab
What type is the sprite array, just spriterenderer?
Yeah. It's a ECS-like system. All other "components" work just fine. The object correctly moves when index 0 is processed. It shows the correct stats when I debug [0]. The only thing I can think of is that the animation part is handled from a different script
But I suppose the references should be correct
^ try a debug log with context and see what object it's actually pointing to
challenge/verify that assumption. there's a bug here because some assumption you have is incorrect, could be this one.
Or just checking the inspector in UnitManager and seeing what it's pointing to
or check in this object with the debug inspector
I couldn't move the Unity window while debugging, but I tried to get it all in frame https://puu.sh/KI7Hl/ef16834df4.png
It seems to have assigned the Unit(Clone) correctly to the SR array
you can also try to https://docs.unity3d.com/ScriptReference/Selection.SetActiveObjectWithContext.html to point at the specific object, thats holding the spriterenderer
Ah, you already debugged it, okay
Oh wait, are you working with an animator?
I've heard the new unity input system is "awful". I've certainly felt a little resistance but my usecase was... farily unorthodox, do people agree with this? If so, what makes it awful? I'm looking to make a local multiplayer game and it seems... okay for this usecase...
what makes it awful?
you tell us. what was the issue they were claiming?
Its not awful, its flexible and easy to learn.
and what logs after your method when you log that specific sprite renderers sprite?
I think most people who say it's awful think it's too complicated and hard to learn
(i disagree)
Oh, I needed to map two players with different schemes to the keyboard
the new input system is very flexible, but that flexibility comes with complexity. there's more of a learning curve than the old one, and there's a ton of ways to handle input using the new system.
afaik, everything except GetAxis (with smoothing) has a 1:1 equivalent in the new system.
that wasn't what i asked in that message, but sure, that's useful info.
that's.. not unorthodox at all, that's just typical local multiplayer
It's not something I nessicarily expect it to cover
maybe you can show the entire script on a paste website
The new input system is an improvement in every metric except for copy-pasteability.
It's a nightmare if you intend to just steal code without learning and a godsend if you want to actually make a video game
I mean its all procedural generated using prefabs, I was just wondering if it completely breaks the materials. I can always fix the lighting and camera effects
I'll try that
Alright well this is good to know.
One less thing I need to do
Thank y'all
!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.
If you are using custom shaders, you have to cover HDRP with them. If its default shaders, unity most likely updates them automatically. But also a lot of options change, are handled differently. So be careful when just switching.
Apologies
I misread
They didn't elaborate on what issues they have with it they just said it was bad and suggested I make my own handler on top of unity's old input system
it's pretty hard to confirm or dispute an opinion that just says "X is good/bad" when no reasoning is provided
Fair enough.
can't read their mind, maybe they just didn't like it based on vibes lol
At minimum it's nice to confirm that people do use it for local multiplayer, which likely means it's good enough for me
input system can be used for all input, it's effectively a superset of the old system
I guess, most people not based on tutorials, are using it nowadays, because its just way easier to handle when setup (my opinion)
https://pastebin.com/JjkJfDea UnitManager
https://pastebin.com/f4AF5HUv AnimationManager
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
most tutorials you'll see with still be using the old system, given that, well, there's years and years worth of input manager tutorials, and only a few years worth of new input system tutorials
Out of curiosity, how is differentiating between multiple controllers done in the old unity input system?
no clue tbh, i didn't get that far before learning the new system
I see
there's a controller 1/2/etc config in the input manager, maybe it's that
It doesn't seem too hard to convert, at least
this might be useful to you (at least in comparison if nothing else) #🖱️┃input-system message
as an example of "input system can be used in a lot of ways"
yeah, as i mentioned, anything aside from smoothed GetAxis has a direct equivalent in the new system
just gotta be familiar enough to make that translation
Hey, So I am trying to add a raycast from the player so it follows my mouse, The ray is being cast from an empty game object in my player which is following my mouse input. My issue is its not accurately following my mouse. This is a feature I am adding where you can throw the ball is this a dumb way to do it? If I cast the ray from the camera that's not really going to work. Any ideas?
Hm, looks right so far. Did you log your sprites[index].sprite for example in update after changing it with HandleWalking? So you can be sure, its switched?
wtf obs is not showing the game window odd..
why are you testing this in scene view
im not obs aint showing the game view
cool, so you just aren't showing the bug then lmao
We'd need to see how this reacts to the scene from the game camera (scene view)
how do you know it's not accurately following your mouse if you don't show where it is in relation to your mouse
draw some gizmos to see in the gameview
also, in terms of ui/ux - how do you plan to resolve depth exactly? as in, what's the intended behavior
eg, if you have your mouse on the edge of the player, should that go towards the camera, parallel to the camera plane, away from the camera?
I fixed it.
you want to raycast against the 3d world from your cameras position to get a hitpoint that you can use to visually attach the end of your line to it. right now you are going from your switcher into whatever is RayTarget.forward, which is basically some local direction not in world space
Honestly just me being stupid. The code worked correctly, but I still had an animator component on the prefab which, I assume, was overriding the sprite change
what are all those arrays for? why not lists
And I was asking about the animator 😂
Well, I did use it initially. But after wanting to try to make my animations manually, I forgot to remove it 😅
glad you fixed it
ECS pattern. It's simple to pass data around if the object's identity is just an int. If it was a list, the identity would change dynamically and it would be difficult to trace
you could have a similar thing with maintaining indices with lists, or even with dictionaries
just without preallocation
but i don't know the context/usecase, so maybe that preallocation makes sense /shrug
-# not a recommendation exactly, just thinking out loud
So from what I can see, you've cast a ray from the player in some forward direction relative to rotation acquired from look input; which is acquired from look action. This can probably produce syncing issues and the drawn ray will not be relative to the mouse position on the screen. The ray direction is definitely moving when the mouse moves but perhaps you should take a different approach.. like cast a ray from the screen-camera to the scene and simply make your object look-draw-a-ray to wherever your mouse had been pointing to relative to the screen. Otherwise, it is moving relative to the acquired input action - just not relative to the object, it would seem.
I could. Maybe another time. If I want to try making a pizza, I wont get better at making pizza if I made spaghetti instead
I'm really just trying out different systems to get a broader understanding of coding in general
i don't see how changing an array to a list would make this not ECS, the usage would be largely the same 
is this a specific requirement with ECS?
Not that I'll stick to this pattern. Just thought it would be interesting to try. Also hence the reason I'm animating manually. It's a challenge
i mean like, what happens if you need a new one but availableIndices is empty 
Making it a list just requires that you change the logic a bit. Using indices just means I pass an int around
not really
you can do the same with a list
a list is just a wrapper for an array that sometimes makes a new array
You'd still have to change some of the logic.
unit[i] attacking unit[unit.target[i]] changes if another element in the list is destroyed or removed
you don't have to remove it from the list, same way you're handling it with the array
however you're "removing" it from the array, you can do the same with a list
my point is i see 2 potential issues to these arrays, and changing them to lists would eliminate those issues while introducing a minor third one (that can be tuned to be less impactful, depending on usecase)
I think I already stated that I'm doing this as a way to learn.
I'm not doing it for efficiency or performance
ok, 1 of the potential issues of the arrays was perf. the other is functionality
what happens if you need a 1001th element? 1000 is arbitrary
a list lets you dynamically handle the amount requirements
😄 Just keeps on going
i am a beginner coder and i am making various side projects to increase my skillset. i try to replicate arcade games (because i have been suggested to do that a lot) and i am currently doing pong. it is a nightmare! could anyone give me some tips? i have tried doing it by using the bouncy physics material on my ball, i have tried making the bouncing myself with basic code, but everything i try has at least one major bug/ flaw that just destroys it all
Isn't that irrelevant without the context?
If I want a game where I need more than 1000 objects, sure. I'm practicing, so array lenght is arbitrary and it's not really important
you're learning, right? so i'm trying to give an opportunity to learn how to make extensible systems without arbitrary numeric restrictions
I've been working with lists up untill now
Lists, Dictionaries, Staks, Queues
I thought I'd try the old fashined way
fair enough, but making these lists would be 2 lines of change
and it wouldn't affect the overall logic of maintaining indices
stack availableIndices
- array entities
+ list entities
new:
- return availableIndices.pop()
+ if !availableIndices.empty():
+ return availableIndices.pop()
+ else
+ entities.push() // or reserve more and push to availableIndices
+ return entities.size() - 1
// exact same code for removal & retreival
I don't see what it is you're not understanding. Why are you so persistent on changing something I'm doing for fun?
...huh? this wasn't an attempt to win you over to lists
sounded like
I didn't come here to ask for improvements or changes. I had a bug and wanted to see if anyone could help me find the issue
i can get not wanting to change just because you aren't interested. but the previous reasons you gave just weren't relevant
What issues do you run into? We need some more information to help, besides, its not working 😉
i'm here to help people learn, and i'm trying to show how lists would be pretty much drop-in while giving a little improvement.
you gave reasons for not using lists that weren't correct, so i disputed those.
Where was I wrong?
i'm not trying to convince you to use lists. i'm just trying to show how they can be used here
By using real physic simulation, you are already "away" from the original pong, which most likely is just a simple angle in out calculation and some checks on the position and size of the sprite against the moving bars. So you can either try to make this 1:1 or even experiment with physics and maybe create a more unpredictable but more fun version
guys..., you wanna use a thread for this?
Well when i use the physics material the ball eventually slows down
And when i do it with code, it sometimes goes into walls
Oh and before it slows down all the bounces are inconsistent
so you gotta check how to move a physics body without "teleportation" by not using transform.position but also maintain a minimum speed for example
#💻┃code-beginner message -> you wouldn't have to change the retreival or removal logic, you can maintain indices in the same way as you are with the array - by just not touching them
i realize my replies here could be somewhat condescending.. that's not my intent, sorry if it comes off that way
Some slow some fast
I am pretty sure i was not using transform.position
I think it was with velocity
Then you gotta check how fast you need your physics to update, if they cant keep up with your game speed.
Maybe show your code, as we are in a coding channel 😉
But i deleted all that code to use the physics material
Well…
Wait is that possible
To make physics update more often
I thought it was always a 0.02 sec or something?
That would be very useful
i guess my real point is - this is an opportunity to learn about analyzing for restrictions and making future-proof/extensible code. i don't know if you're already experienced with that and thus don't care in this learning instance, since i'm not in your head. it's your choice whether you want to use that opportunity or not, but if you present objections that don't apply then i'm going to dispute them
Though more resource intensive
Okay. I'm not sure you read the code I pasted.
The target[] array is an int array. A unit having a target means that it's acting towards an index corresponded to the array. If a unit is moving towards target[5], and I want to remove target[4], nothing will happen to [5] because that unit's data is attached to that index in an array. If I unit.RemoveAt(4), suddenly the corresponding indices will shift down, and the unit will now target what was previously target[6].
That's what I mean by "changing logic". I understand that you can change things up. I could allocate an identity int within one of the struct. I could use a dictionary with ints as keys. But that's essentially changing the logic
no, you don't have to change anything there at all. you don't have to use RemoveAt.
how are you "removing" with the array currently? just saying the index is available, or also setting it to null?
you can do the same with the list.
public bool[] indexOccupied;
using a dictionary with ints also doesn't change the logic, just the underlying data structure
sure, you can make a list for that too. my point is- you don't have to change the logic at all.
a list is a thin wrapper around an array, you can use the list like an array plus the "resize" operation.
Unless I want to remove things from it...
you can "remove" things in the same way as you are removing from the arrays you already have
RemoveAt removes the data and the slot. here (in the current array case, and changing the array to a list) you just remove data and not the slot
So now we've moved the utility of lists to be equal to that of arrays, if I know I wont pass the array size
the benefit being pre-made dynamic allocation. this was my entire point, yes.
that's what i meant by it being "drop-in" for this usecase
I don't often ask for help in here. It can be a bit dreadful trying to ask for something and it's often met with "Why would you.." or "Why don't you.." with something completely unrelated to the context I bring
is it that it sounds condescending?
It's that there's a persistence with getting a point across rather than to just meet the people where they're at with their questions.
it's a pretty effective thing to point out something that might not be ideal and challege the assumptions that wrote that solution (in general)
this isn't just a q&a forum, this is intended to help people learn
that's what i'm trying to do here
that's what "why are you doing X" is intended to get at - it's easier to build off of reasoning once it's verbalized
If I say I want to learn to do a design revolving around arrays, it doesn't help if I'm being told to use something other than arrays
maybe this would clear it up -
the main "issue" (not really an issue in the specific case, but something that could be improved) is the static allocation.
dynamic allocation would solve that "issue", making it more generalized
that's what lists are, dynamically allocated arrays, with a bunch of extra operations. you don't need those extra operations, so you can just ignore them
you could do dynamic allocation yourself if you wanted too, that's also a pretty nice thing to learn
and again - i'm not telling you to not use arrays. i'm pointing out that lists could be used here.
lists are just a thin wrapper around arrays. the change i'm suggesting would have 90% of the use still treat it as an array.
I'm well aware of what lists are. Thank you
Can you guys either go into a thread or just stop? This is getting frustrating to read along... everyone made their point.
I apologize if I sounded a bit hostile. It wasn't my intention.
This is what I have got, The ray from the player is following the ray from the camera went and tested it out and it does follow but its not accurate at all.
using UnityEngine.InputSystem;
public class AimFromMouse : MonoBehaviour
{
[Header("References")]
[SerializeField] private Camera mainCam;
[SerializeField] private Transform playable;
[Header("Ray Settings")]
[SerializeField] private float rayLength = 100f;
[SerializeField] private LayerMask aimMask;
private RaycastHit hit;
void Update()
{
CastCameraRay();
}
private void CastCameraRay()
{
Vector2 mousePos = Mouse.current.position.ReadValue();
Ray cameraRay = mainCam.ScreenPointToRay(mousePos);
Debug.DrawRay(cameraRay.origin, cameraRay.direction * rayLength, Color.cyan);
Vector3 origin = playable.position;
Vector3 direction = cameraRay.direction;
Debug.DrawRay(origin, direction * rayLength, Color.red);
if (Physics.Raycast(origin, direction, out hit, rayLength, aimMask))
{
Debug.Log("Playable ray hit: " + hit.collider.name);
}
}
}
private void CastCameraRay()
{
Vector2 mousePos = Mouse.current.position.ReadValue();
Ray cameraRay = mainCam.ScreenPointToRay(mousePos);
Debug.DrawRay(cameraRay.origin, cameraRay.direction * rayLength, Color.cyan);
Vector3 origin = playable.position;
Vector3 target = cameraRay.GetPoint(rayLength);
Vector3 direction = (target - origin).normalized;
float distance = (target - origin).magnitude;
Debug.DrawRay(origin, direction * , Color.red);
if (Physics.Raycast(origin, direction * distance, out hit, rayLength, aimMask))
{
Debug.Log("Playable ray hit: " + hit.collider.name);
}
}```Player direction is incorrect
This would have them pointing to the same point some distance away relative to the ray length.
Ideally, you'd normally do a ray cast first to see if there are objects in the way and would use that hit-point as the target for both the camera and player rays.
I am still not understanding why its not accurate? my mouse will be on for e.g. a wall and there are no debugs but if I keep moving up then the debugs will happen. Do I need to adjust the camera ray as well?
do both hit points need to be touching? I mean like the tip of the ray do they both need to be touching?
private void CastCameraRay()
{
Vector2 mousePos = Mouse.current.position.ReadValue();
Ray cameraRay = mainCam.ScreenPointToRay(mousePos);
Vector3 target = cameraRay.GetPoint(rayLength);
Vector3 origin = cameraRay.origin;
Vector3 direction = (target - origin).normalized;
float distance = rayLength;
if (Physics.Raycast(origin, direction * distance, out hit, rayLength, aimMask))
{
Debug.Log("Camera ray hit: " + hit.collider.name);
target = hit.point;
distance = (hit.point - origin).magnitude;
}
Debug.DrawRay(origin, direction * distance, Color.cyan);
origin = playable.position;
direction = (target - origin).normalized;
if (Physics.Raycast(origin, direction * distance, out hit, rayLength, aimMask))
{
Debug.Log("Playable ray hit: " + hit.collider.name);
target = hit.point;
distance = (hit.point - origin).magnitude;
}
Debug.DrawRay(origin, direction * distance, Color.red);
}```
Where is there an 4, and why??
This doesn't look unity related
Its C#
You could try asking the c sharp discord server
!csds
There's no command called
csds.
also your second image litterally explains this
Yea but would'nt it work with 3?
it's wrong lmao
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
is this ai generated?
this looks one of those "learn programming apps" which are almost entirely ai generated
maybe it's just desynced - the code was changed the description wasn't updated or vice versa
Idk until then it was really good
well regardless, this isnt really the place to find help for just general c# stuff
this server and channel are for unity specific issues
Ok, but still thanks
(it's !cs btw)
Hi I was just wondering if it was possible to detect if an object is colliding with an object based off of a tag and when it does it reloads the scene. Except both objects have the same tag so I want the main object to not be detected but rather the other object. If that makes sense XD
heres wat my code looks like so far.
using UnityEngine;
using UnityEngine.SceneManagement;
public class InsideObject : MonoBehaviour
{
private string currentScene;
public string[] tags;
private void Start()
{
currentScene = SceneManager.GetActiveScene().name;
}
private void OnCollisionEnter2D(Collision2D collision)
{
foreach (string tag in tags)
{
if (collision.gameObject.CompareTag(tag))
{
Debug.Log($"Collided with {collision.gameObject.name} (tag: {tag}). Reloading scene.");
SceneManager.LoadScene(currentScene);
return;
}
}
}
}
basically the issue I'm coming across is that its reloading the scene because the object with the script has the one of the tags in the array. I want to detect for the other objects not the main one.
Hmm, I must have been using it wrong all of this time
#💻┃code-beginner message
the bot was changed, the commands were probably changed with that migration
you have to designate some way of distinguishing the target object
so wat do like a private game object var. and call it something like mainObject and then find said object in the start method
up to your design. i'm honestly not sure what the situation/context is
This is what it looks like why is it still not accurate??? its not even going to where I am pointing its on the Z axis / spinning.
sounds like a XY problem, maybe explain what you are doing @spare summit
or what you want to achive
so basically I'm having an issue with my crates that they get stuck inside of eachother. I want to detect that and then correct it. Thats basically the idea I have with fixing the bug. But I can't figure out how to detect the crate with out detecting the main crate itself
@frail hawk
the reason why this is happening is the system I have with the movement script where it stops the movement script from working if a crate is next to another crate. But this created the bug I show in the video and I've kinda been putting it off for some time now
Show us how it looks from the scene view as well while you're moving he mouse in the game view
Likely the mask isn't correct and you're firing off way into the back ground
how would I make sure an object stays on the grid in play mode. Like the object doesn't go into whole numbers they only stay on .5's like 2.5, 3.5, 5.5 that kinda thing
Probably something to do with your mask in regards to the ray cast
@red igloo The code provided should work. You'll need to debug to figure out why yours isn't working as intended.
In my example, playable is the sphere.
Your logic that moves items needs to round the position to the steps you want. Ideally you also store the non rounded version too so slow movement is still possible
I have checked multiple times nothing seems wrong.
For some reason when I increase the ray length I can move the ray behind the player
Ok so for some reason the issue was the ray lenght I set it to 200 and its literally working now but this feature is for throwing a ball I want to have a max distance. The ray lenght value 5 was perfect but if I lower it then the issue will reoccur The issue was the layerMask I removed it and its now working
Hello, I am making a platformer game with rooms.
I would like my player to switch to another room smoothly (keeps reletive pos and velocity) when it touches an object. Ive tried and failed to make a script but I get an error when I use it.
If someone can tell me whats wrong with my script or give me a link to a source that explains how to do this it would be greatly appreciated
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
public class switchRooms : MonoBehaviour
{
[SerializeField] int switchTo;
static string switchToText;
GameObject switchedTo;
[SerializeField] GameObject player;
static bool switched;
static Vector3 playerPosition;
static Vector3 playerVelocity;
int goToRoomsInScene = 0;
int goToRoomIndexTracker = 0;
GameObject[] goToRoom;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Awake()
{
GameObject[] allObjects = FindObjectsOfType<GameObject>();
foreach (GameObject obj in allObjects)
{
if(obj.name.StartsWith("goToRoom"))
{
goToRoomsInScene++;
}
}
goToRoom = new GameObject[goToRoomsInScene];
for (int i = 0; i < allObjects.Length; i++)
{
if(allObjects[i].name.StartsWith("goToRoom"))
{
goToRoom[goToRoomIndexTracker] = allObjects[i];
goToRoomIndexTracker++;
}
}
}
// Update is called once per frame
void Update()
{
if (switched)
{
for (int i = 0; i < goToRoom.Length; i++)
{
Debug.Log(goToRoom[i].name);
if (goToRoom[i].name == switchToText)
{
switchedTo = goToRoom[i];
Debug.Log(goToRoom[i].name);
}
Instantiate(player, new Vector3(switchedTo.transform.position.x + Math.Sign(playerPosition.x), switchedTo.transform.position.y + Math.Sign(playerPosition.y)), Quaternion.identity);
player.GetComponent<Rigidbody2D>().linearVelocity = playerVelocity;
switched = false;
}
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "Player")
{
playerVelocity = player.GetComponent<Rigidbody2D>().linearVelocity;
playerPosition = player.transform.position;
switched = true;
switchToText = $"Room {switchTo}";
SceneManager.LoadScene(switchToText);
}
}
}
rather than a fixed distance from the camera you should be using a Plane and Plane.Raycast
Ive tried and failed to make a script but I get an error when I use it.
Telling us what error you saw would go a loooong way towards helping you
ofc sorry
Also: switchRooms is not a good class name for several reasons:
- Class names should be nouns not verbs. This is a component in the scene that may do something. "room switcher" would be better.
- Class names in C# should use PascalCase- so RoomSwitcher for example
ok and which is line 58?
Instantiate(player, new Vector3(switchedTo.transform.position.x + Math.Sign(playerPosition.x), switchedTo.transform.position.y + Math.Sign(playerPosition.y)), Quaternion.identity);
The only thing on this line that could cause this error is if switchedTo is null
Which makes sense because it's very possible in your logic there for it to have never been assigned to anythiong
if (goToRoom[i].name == switchToText)
{
switchedTo = goToRoom[i];
Debug.Log(goToRoom[i].name);
}
Instantiate(player, new Vector3(switchedTo.transform.position.x + Math.Sign(playerPosition.x),```
If this code runs and the if statement does not get entered, you will still have switchedTo as null
and then you're trying to get the position on a null reference, bad.
I see, thank you! have a great day
for future reference, use mp4 so it embeds in discord
Still Surprised that discord doesn't have a mkv support. Not like it's a extremely rare format or anything.
true
Conversion and bigger files is almost likely the reason to not drop mp4
dropping mp4 was not part of that message
Yeah, mp4 is more universal. I was moreso refering to how common mkv files were
since they're often exported from recording sessions
totally agree, just wanted to state, that there is rather one standard than trying to cover more not so frequently used formats for broad device support. Thats all 😄 Not gonna start another discussion here
The thing is, there's no such thing as an mp4 format. It's a file type that contains many kinds of video encoding. It's actuall the h.264 encoding that makes it embeddable. The file type doesn't actually matter, the encoding matters
What is the proper syntax for wanting to check if a compared value is greater than a negative number? Currently with this script the cube rotates up to the max value, rotates the other direction, but does not reverse course again once it exceeds the stated negative value (min Rot)
` if (reverseRot == false)
{
print("Rotating to the right");
transform.Rotate(0,0, rotationSpeed * Time.deltaTime);
if (gameObject.transform.eulerAngles.z >= maxRot)
{
print("I am at max rotation.");
reverseRot = true;
return;
}
return;
}
else if (reverseRot == true)
{
print("rotating to the left");
transform.Rotate(0, 0, -rotationSpeed * Time.deltaTime);
if (gameObject.transform.eulerAngles.z <= minRot)
{
print("I am at minimum rotation.");
reverseRot = false;
return;
}
return;
}`
x > some_negative_number
it being negative doesn't have an effect in the comparison
the issue might be in reading the eulerAngles though. that's typically not regarded as reliable afaik
it's not the canonical representation of the rotation
The main problem with your script is you're trying to do logic based on simple comparisons of a single component of euler angles
store the current rotation amount yourself and only set it to the transform, don't read it back
i honestly don't see how you got to that statement of dropping mp4
"we should add webp support"
"can't, we can't drop png, it's more ubiquitous"
If I use a plane.raycast can I have any distance? right now I need to have the distance 200 if I change it any lower the ray won't follow the mouse properly.
And I actually dont care. You do you 👍
the human psyche is such a weird thing
make a local variable for my objects current rotation? I'm a bit confused
Why would simply saying "If X rotation is -90 go in reverse" also not work?
what if it's 270 instead
It might not be -90
it might be 270
Likely because the property that returns the euler angle is an interpreted value as the Transform component's quaternion could be interpreted differently
yep
instead of
transform.value = transform.value + delta;
```you would do
```cs
value = value + delta
transform.value = value
Basically, you should only ever write to euler angles, not read from it
Because you could literally do:
eulerAngles.z = value;
Debug.Log(eulerAngles.z == value);
and get false
(pedantically - you can read from euler angles if you just store the Vector3 yourself, but not Quaternion.eulerAngles or Transform.eulerAngles)
I mean, if you really want to look at it you can but it shouldn't be thought to be the value that is actually used by the Transform component.
When you do transform.eulerAngles, it will compute a possible euler angle expression that represents the orientation. There's an infinite number of euler angles values for any given rotation, so you can't depend on that being a specific one
Gotcha. I'll do that when I get back. But that makes sense.
why wouldn't you be able to have any distance?
idk the way I have it set up right now the lenght of the ray is 200 if I got lower the ray will no longer follow my mouse i.e. if I move the cursor behind the player the ray wont go there.
You do realize there are two raycasts involved here right
what's a good 2d top down engine to use?
you need:
- A plane raycast (unlimited range) to find the point the mouse is projecting onto on the x/y plane the player is on.
- a raycast from the player towards point found in step 1, with some max range.
you can use unity
considering you are in the unity server
lol thanks but like do i need something like this https://assetstore.unity.com/packages/templates/systems/topdown-engine-89636
no, you dont need it
this is just an asset to make making these kinds of games faster and easier ig?
but as a beginner i would highly recommend you go the manual route
Not really clear to me what this does for you other than a character controller and camera controller script, which you will probably need to tweak anyway
i checked it out when it was on sale, its an ok asset but kinda useless
it does nothing you can do on your own
it has some good example projects and i guess it can be useful in some situations
moving platforms, an advanced room system, persistence, smart input management, progress management, collectibles, a loot system, kills manager, destructible crates, keys and chest/doors, and more. Also achievements, dialogues, progress management, save and load, and tons of other useful stuff!
This stuff is all so bespoke as to most likely be useless.
it's trying to be a "do everything" asset
oh are these the guys behind Feel? I actually considered buying that a while back
feel is just a tween library with premade samples you can use
kind of
That’s kind of underrepresenting it. A lot of it is tween-based but it also has components to simplify particle system and audio handling. Overall I think it’s a very good tool if you don’t want to bother with cooking up solutions for every little piece of feedback you want to give to the player
I agree though on their “game engine” assets. Seems like it would pigeonhole your designs
Guys pls help me 🙏 . I don't know why this code doesn't boost player's speed:
private void OnCollisionEnter2D(Collision2D collision)
{
grounded = true;
if (sliding)
{
if (collision.gameObject.CompareTag("enemy"))
{
Debug.Log("sliding into enemy");
rb.linearVelocityX = rb.linearVelocityX * 10f + side * 25f;
}
}
}
(side is a variable that when the player presses 'D' it has the value of 1, 'A' -> -1)
im sorry but did you individually wrap each line of the code in an inline?
i tried to do 1 ` at the beginning and one at the end but it didn't work
if side is a range of 1 to -1 then what happens if its 0 and you arent moving horizontally
Oh! This is great, thank you! I was wondering if there was a way like this but never looked it up 🤔
i don't want the player to gain speed when they are not moving, i checked the variable and it works as it should be
i think it might be a physics issue actually
Does the log print?
no errors
if you hit the enemy and collide with them, then you set your velocity to some high number, the physics solver might be applying some sort of opposing force to slow you down
Does "sliding into enemy" print?
to prevent you from phasing through the enemy
yes
wait it actually doesn't
bruh that would be something to mention first
means youre failing somewhere in the 2 conditionals
youre either not setting the sliding bool to true, or your collision object doesnt have the enemy tag
add another debug under the if "sliding" and see if that triggers properly
Or OnCOllisionEnter2D just isn't running at all
the sliding works just fine
Are you overwriting rb.linearVelocity after setting it here?
i figured it out! after the player touches the enemy, the enemy's tag switches to "deadEnemy" and it probably is doing it faster than the if statement can check the tag. Sorry guys for trouble, I'm such a dumbahh, thanks for your help!
it's not about "speed". No two lines of your code are ever running at the same time. It's about which order those things happen in.
Quick question, does base.Function() call the previous inhertiance or the first?
For example, would this print "1 2 3" or just "1 3"?:
public class BaseClass : MonoBehaviour {
public virtual void Function() {
Debug.Log(1);
}
}
public class SecondClass : BaseClass {
public override void Function() {
base.Function();
Debug.Log(2);
}
}
public class ThirdClass : SecondClass {
public override void Function() {
base.Function();
Debug.Log(3);
}
}
This is something I'd probably need to run to know for sure, but thankfully you've got a perfectly reasonable example. I'd just slap that into a project and 
yeah definitely 
but it would indeed print 1 2 3. base.Function() would call the previous version of the method in the inheritance line
it calls the one on the class you directly inherited from
ThirdClass base.Function will call SecondClass Function
Sorry for the late response, I have been trying to figure this out and this is what I have so far. I never really used plane.raycast so I don't know if I did it right but as you can see it doesn't follow the mouse properly and when I move the cursor infront of the player the ray doesn't go in front of the player.
private void CastRay()
{
Plane playerPlane = new( -mainCam.transform.forward, mainCam.transform.position + mainCam.transform.forward * 10f);
Ray mouseRay = mainCam.ScreenPointToRay(Mouse.current.position.ReadValue());
if (playerPlane.Raycast(mouseRay, out float distance))
{
Vector3 targetPoint = mouseRay.GetPoint(distance);
Vector3 direction = targetPoint - playerSwitcher.currentPlayer.transform.position;
if (Physics.Raycast(playerSwitcher.currentPlayer.transform.position, direction, out hit, maxRange, aimMask))
{
Debug.DrawLine(playerSwitcher.currentPlayer.transform.position, hit.point, Color.red);
}
else
{
Debug.DrawRay(playerSwitcher.currentPlayer.transform.position, direction.normalized * maxRange, Color.green);
}
}
}
before we continue here I want to make sure I fully understand what you're trying to actually accomplish here. Is the player meant to be able to aim only horizontally and vertically (relative to the camera)? Or also in and out (like the z axis)?
My understanding was you essentially had a 2.5D game and you wanted the player to be able to aim only on the gameplay plane
but now in this video I see the player walking in 3D space
So what's the actual goal here?
maybe they are missunderstanding what 2.5d means in this scenario? 
When I say "2.5d game" I mean 3d art that can only move side to side and up and down like an original 2d mario sidescroller just with 3D art
when i personally think 2.5d i imagine a game that uses 2d sprites in a 3d enviroment
to me it just sounds like youre describing a 3d sidescroller
octopath traveler being a good example ig
or paper mario
The point is the gameplay happening on a 2d plane
Anyway I need a description from @red igloo about what this game mechanic is supposed to be doing and how they want it to work
If as a player my mouse is on the floating cube in this picture, what should happen? What if it's on the wall that's in shadow on the left, or the wall in shadow deep in the distance?
The game is 3D not 2.5D, this is a throw player feature. The real player is the ball I can switch to the capsule player and throw the player I.e. ball. I want to be able to throw the ball anywhere with no restrictions. Sorry for the confusion:p
If the mouse is on the cube or behind it or whatever it doesn't really matter you can throw the ball anywhere
yes but I'm asking specifically WHERE will the ball be thrown if the mouse is there?
will it be thrown at the cube? Will it be thrown up and to the left of the player on the same plane the player is at?
This screenshot from your earlier video illustrates what I mean. The ray from the camera is the cyan one. But your mouse is sort of hovering over the back wall right? So in this scenario should the ball be getting thrown at the back wall? Or should it be getting thrown at this point in the air that is an arbitrary distance from the camera?
Imagine extending the cyan line out to infinity. We need to decide where along that ray the "throw target" is
Should it be whatever physical object we see that is closest to the camera along that ray?
So in this case, the back wall?
This screenshot maybe shows it even better.
halo
is there any reason as to why I can't or shouldn't grab UI objects as gameObjects in serialized fields?
Assuming you're talking about UGUI (the one with Canvases etc), no there is no reason you shouldn't be able to do that
Can you show exactly what you are trying to drag and where you are trying to drag it to?
Why would it be bad practice?
That's how Unity works
how are you defining the field?
can you show the line of code
and what exactly youre trying to drag into it
Ahh sorry lol, the ball should be thrown toward the point where the ray EXACTLY hits doesn't really matter if the mouse is hovering else where and the ray is else where but I would like both to be in sync if thats possible.
when i write Lander.OnUpForce += Lander_OnUpForce; it should auto create a function with that name and add a bunch of stuff to it (following a tut) but for some reason that isnt working for me , its not autocompleting it and i have to write that function myself , why?
This is vague
so you mean the nearest physical object on its path?
Or what?
!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
• :question: Other/None
It isn't supposed to automatically make the method. What it should do is give you the option to auto create it in the little light bulb context thing that pops up
The tutorial person may also be using a different IDE that makes the experience a little nicer
I'm not asking about rays (yet), just about what your desired gameplay behavior is
ye but it isnt
In this screenshot where should the ball be thrown
i doubt that cus he said its a ultimate beginner tut
I mean it looks like you already have the function so
youtubers say a lot of things
ye cus i wrote it manually , i need it like 3 more times
ig imma write everything
I would also advise against this System.EventArgs pattern in UNity. It creates a lot of unecessary garbage
And passing in the sender as an object is just silly
im trynna make the partice system only activate on specific occasions
ok? That's not related to the point i was making
I'm just saying the delegate type they chose for the event is silly. In fact you're not using any of the arguments at all so System.Action would have been fine.
(this would be something you have to change in the LangerControls script as well as here)
anyway I'm not sure why your IDE isn't helping you out here
the relevant part for this stuff would be "delegates" and "events"
Ok so what I want is a throw player feature so right now I have a separate script where the main player which is a ball when entering the trigger zone near the capsule and presses E you switch to the capsule player and the ball disappears. This script that I am doing now will allow the player to throw the main player (Ball) by holding right mouse button. I am going to add a aim feature where it shows you where your about to shoot the main player.
Yes... I'm well aware of all this I'm literally trying to ask you how this throwing feature should behave with regard to the mouse and camera positions
Specifically these questions about where the ball should be thrown
Is this a language barrier problem? Are you not understanding the question I'm asking?
The #1 most important part of software development is being able to explain what it is exactly that you want, in detail.
Without that we can certainly write some code that does something, but it might not be the thing you want it to do.
Sorry just a bit confused / tired, I'll try explain it better. The throw should be unrestricted in 3D space. I ray cast from the camera through the mouse to get a target point. If the ray hits something, the ball is launched from the capsule toward that hit position. If it hits nothing, the ball is launched toward the ray's max distance.
void Update()
{
for (int i = 0; i < LegIKTargets.Length; i++)
{
Vector3 target = transform.position + legOffsets[i];
float distance = Vector3.Distance(LegIKTargets[i].position, target);
if (distance > legThresold) {
GroundLeg(i);
}
}
}
Why doesn't my distance check work?
My guess would be that distance > legThreshold is never true. Log both values and see
for some reason my distance is always over the threshold even when im not moving the leg
when i higher the threshold this happens
Did you log distance? Is it the value you expect it to be?
nope, it gradually increases, its at 9 even when the current leg position is the same as the target
So, if distance is what you expect it to be, and legThreshold is what you expect it to be, then it appears it's working fine
distance should be 0 if my legs are at the target
since the leg would be no distance from the target
Okay, so then go one step back: Log LegIKTargets[i].position and target and see which one isn't what you expect
i think its because the target and leg arent on the same y
Id upgrade to a debugger for something like this
ok then you need to be doing:
- a physics raycast, with a max range of like 1000, to find the point to throw towards
- throw towards that point.
I guess the second raycast is to see if it will hit any obstacles on the way towards that point?
im fallowing a tutorial for making a hex based grid and ive gotten to the part in the tutorial where they make a auto genorating mesh for it but its super hard to fallow along and it looks like the skip parts of the code does anyone have an recources for this ?
I'm sorry I know other people are asking questions here too and my one is relatively petty can I still ask it?
It's time to sleep anyway so let me ask tomorrow and not interrupt anyone rn
there is no line or queue. just ask your question. you'll never get the chance if you keep waiting for other people to finish getting help . . .
what do these mean "()"
those are parentheses, what they mean depends
👍
alr what would they mean at the begining of start and update
for functions its an invocation operator
you are probably better off learning these things from some sort of c# tutorial
because these are the very basic of the basics, language agnostic as well
IEnumerator GroundLeg(int leg)
{
RaycastHit hit = new RaycastHit();
Vector3 localOffset = legOffsets[leg];
Vector3 target = transform.TransformPoint(localOffset);
Vector3 startPos = LegIKTargets[leg].position;
// Create a ray from the target downwards for the leg
Ray ray = new(
target + transform.up * rayCastHeight,
Vector3.down
);
if (Physics.Raycast(ray, out hit, rayCastDistance, rayCastLayerMask))
{
float elapsed = 0f;
while (elapsed < legDurationMove)
{
// Parabolic leg movement with animation curve
elapsed += Time.deltaTime;
float t = Mathf.Clamp01(elapsed / legDurationMove);
float height = curve.Evaluate(t) * stepHeight;
Vector3 pos = Vector3.Lerp(startPos, hit.point, t);
pos.y += height;
LegIKTargets[leg].position = pos;
yield return null;
}
LegIKTargets[leg].position = hit.point;
}
}
Hi again, small problem, why aren't my spider legs affected by the rotation of the spider? like for example I face my spider against a wall and its legs don't move to the wall
is it worth it to use a kinematic rigidbody for more control over my player
2d platforming game btw
why does spline animation mess with the z component when neither the map nor the scene have different z components?
most controllers are kinematic, so yes