#💻┃code-beginner
1 messages · Page 133 of 1
yeah that's the work around
oh interesting-- that wasn't the case for me but good to know jic! Thank you again!
Alright, the bullet now shoots in the correct direction but is shooting from the same spot regardless of where the character is facing
The video is definitely helping me organize my code better aswell so thanks
get the position and direction of the player and grab a position a unit or so ahead of their forward direction
I believe it is pulling from its location, I think I may have modified it's spawn on accident
I'll review my code as I'm adding comments to see what's messing with it
what you may be doing is getting an offset of the player position but in world coordinates
I need help with moving VisualElements programatically
// Create the image on root
_icon = new Image();
panel.visualTree.Add(_icon);
_icon.style.position = Position.Absolute;
// Make it follow this visual element
_icon.schedule.Execute(() =>
{
Vector2 direction = new Vector2(slotContainer.resolvedStyle.left - _icon.resolvedStyle.left, slotContainer.resolvedStyle.top - _icon.resolvedStyle.top).normalized;
Vector2 newPosition = new Vector2(slotContainer.resolvedStyle.left, slotContainer.resolvedStyle.top) * direction * speed * (executionTime * 0.001f);
_icon.style.left = newPosition.x;
_icon.style.top = newPosition.y;
}).Every(executionTime);
This is not working somehow
Yep, it's offset by .5 on the x coordinate, thanks
All it does is stay on top left corner of the root
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
maybe the ide just telling ya that this code wont execute
You are assumably looking at it when using the Editor? Not when built?
anyone have an idea as to why the code isn't working? its c# and im trying to teach myself with some vids rn any help is appreciated 😁
good starting point is to learn to print to console
in unity we use Debug.Log
it can print out of the contents of a variable as well as strings
Not enough force.
More accurately you should be using ForceMode.Impulse
in place of the rb.AddForce?
so instead i would do something like
rb.ForceMode.Impulse(Vector3.up * 500);
would that work 🤔
That doesn't look like proper syntax
oops sorry i shouldve mentioned i found out the error
it was on line 14
RigidBody should've been Rigidbody
took me half an hour to find 😠
rb.AddForce(..., ForceMode.Impulse);```
Configure your !IDE and never lose time to spelling mistakes again
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
In place of? No. It's a parameter to AddForce
Can someone explain why you would call a delegate using an event instead of just running the functions subscribed to the event?
The delegate just defines what kind of functions can subscribe to the event
So basically like an if check?
more than welcome, brackeys was a key part of me starting and understanding both unity and c# code
now i study both at university
When the thing that fires the event shouldn't know about the functions.
I have a custom animator that fires an event when the time changes, why would that animator want to be explicitly hooked up to every inane thing that wants to read that time? It shouldn't
I legit don't see a difference except the extra roundtrip:
using System;
public class EventRunner
{
public event OnEventDelegate OnDelegateEvent;
public delegate void OnEventDelegate(Object sender, EventArgs e);
public event EventHandler OnNormalEvent;
public void Run()
{
OnNormalEvent?.Invoke(null, EventArgs.Empty);
OnDelegateEvent?.Invoke(null, EventArgs.Empty);
}
}
public class Program
{
public static void Main()
{
EventRunner eventRunner = new EventRunner();
eventRunner.OnNormalEvent += MyFuncNormalEvent;
eventRunner.OnDelegateEvent += MyFuncDelegatEvent;
eventRunner.Run();
}
public static void MyFuncDelegatEvent(System.Object sender, EventArgs e)
{
Console.WriteLine("RunDelegateFunction ran");
}
public static void MyFuncNormalEvent(System.Object sender, EventArgs e)
{
Console.WriteLine("MyFuncNormalEvent ran");
}
}
This is a dumb example
Hello, I've been following a YT tutorial on making a dialogue scene code. The code here has 0 issues and errors, but when played, does not show the output the code is supposed to give. Can anyone help pinpoint the mistake?
hold on wrong code
Use the debugs and check whats called and whats not
yes it shows in the console that the code is active but its not making any changes to the scene in the game
which logs ? changes to scene? what you mean?
you're asking me to check the debug log right?
"it shows in the console"
which one
so if you press spacebar nothing prints?
nope, and not only that this script is part of another script that is supposed to be triggered when a button on the game is pressed
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'm actually thinking it might be this script that holds the problem bcs there are no colors on the FindObjectOfType code (which is a stupid reason probably, im still new)
Your code looks very underhighlighted, are you getting proper autocomplete and error highlighting?
..i dont know, I dont understand how its not highlighted and just assumed its normal
!ide it's not
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
if i delete the FindObjectOfType, the rest of it gets highlited
so the problem is that?
the link said i need to make sure my visual studio is up to date and it is though
It says a number of other things also
screenshot the whole VS editor window too
um, like this?
If it says Miscellaneous Files, it's not configured properly
not configured
what does that mean and what am i supposed to do to solve it?
follow the bot message
that dont even look like VS 2022
but it says its there are no updates needed
does that mean i have to delete and install the 2022 ver then?
i see
because it's not a regular update, it's an entire other version of visual studio. you don't need to install 2022 if you don't feel like it. but it is a decent improvement over 2019
ohh
^ faster, better intellisense etc.
follow the bot's instructions like you've been told #💻┃code-beginner message
what is the dropdown list?
was visual studio not listed in the options for the external script editor setting?
it was and i selected it already
then why are you attempting to follow the instructions for when it isn't listed in that settings menu?
i thought i was supposed to follow all of the instructions of all of the links
you are, but you should also apply some common sense. the instructions immediately before that are to select Visual Studio in a dropdown menu for the External Script Editor setting. this immediately follows it for if it isn't listed or you want to select a different/custom version of it. you do not need to do that part if you've selected the version you want to use already
It does say Select one:
If VS is selected in the External Tools preferences then that part is done. Make sure VS has the Unity workload installed in the VS Installer and the VS Editor package is updated in Unity
select the Unity Registry in the package manager if you do not see it listed in the In Project view
ah, i checked and its already installed and ✅
make sure to restart visual studio by closing it then double clicking a script from within your project after completing the guide to ensure that it reloads the project
ok i did it
does it still say Miscellaneous Files?
no
the code looks like this now, but it still doesnt make any changes in the game itself
DialogueManager isn’t saved
there's also an error in this script underlined right there 🤔
Also what is the underlined error?
FindObjectOfType
prob deprecation nvm thats 2023 I think
its still not colored
hover the error
wait the underline is gone and the FindObjectOfType is colored now
i cant screenshot the hover description but it basically just says the code with a (+1overload) at the back
its fine then
but the code still doesnt make any changes
did you save DialogueManager
use the debugger and step through
put some breakpoints and check your variables
in vs is called Attach to Unity
prob one of the first tools you should learn
oh wow apparently unity has this instruction page
https://unity.com/how-to/debugging-with-microsoft-visual-studio-2022
never noticed
Why does this work
transform.position = Vector3.zero;
But this does not?
transform.position = new Vector3.zero;
have error and idk why]
Because new Vector3.zero; is not a thing, you cannot new a property.
Vector3.zero; returns a new Vector3 with the coordinates (0, 0, 0). You can't call new on it, it's not a type
well, not showing what the error is won't help anyone fix it
body is rigidbody2d
where to see error
like i can't even run it
'Vector2' is an ambiguous reference between 'UnityEngine.Vector2' and 'System.Numerics.Vector2'
Ok, i hear you, but am still a bit confused.. why does this work then?
transform.position = new Vector3(0, 0, 0)
Because Vector2 is a type, and you are creating a new instance of it
via its constructor
Oh, i need to double verify that, that works
so what shouldi do
Sorry, I wasn't replying to you, you had a different issue.
Don't use: using System.Numerics
thanks, i wasnt able to open the first link
use what le
Thanks
The using statements at the top of your file; you have that, and you shouldn't be using that namespace
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformAttach : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Rigid")
{
other.transform.parent = transform;
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Rigid")
{
other.transform.parent = null;
}
}
}
I've created this code to make player stay on my moving platform, i made it move by using animator with "Animate Physics" Everything seems okay till the platform starts moving. Meaning that i cant move on it, my ability to move my player comes back after it stops. Whys that?
ok so i tried using the debugger and selected the codes to see what happens when the game is played but nothing exactly happens?
the code still make 0 changes and it doesnt show me why
Are you getting any errors?
parenting for movement wont really be that good, and it seems your movement system is via the animator. Combining the animator with another movement system (a transform moving) isnt likely gonna work or have expected results. Not really sure what the physics part is for, the docs tell you what animatePhysics is for
https://docs.unity3d.com/ScriptReference/Animation-animatePhysics.html
How are you moving the player?
Im moving my player by rigidbody.moveposition
ah is the platform moving by animation?
Yes.
i dont think so? im kind of confused on what to do
the combination of MovePosition and having the parent also move might be causing weird results in that case then, can you show the movement code?
Yeah right
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementScript : MonoBehaviour
{
public float speed;
private Rigidbody rb;
public Transform orientation;
float horizontalInput;
float verticalInput;
public Vector3 MinHeight;
public Vector3 StartPoint;
Vector3 moveDirection;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
void Update()
{
MyInput();
}
private void FixedUpdate()
{
MovePlayer();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
}
private void MovePlayer()
{
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
rb.MovePosition(transform.position + moveDirection.normalized * Time.deltaTime * speed);
}
}
very basic one
i dont think so? im kinda confused on what to do here
hello there! I am just getting started on my game making journey and wanted to see if anyone has any tips on how to start learning code? i dont want to get stuck in youtube hell and just repeat tutorials
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
also make sure you know your c# before diving too far into unity
thanks!
i managed to do it but it's not exaclty at the edge of the screen
what are you trying to do? (game looks great btw)
the arrow , it should point towards an objective at the edge of the screen , i folowed a tutorial for 2D and made it for 3D but i have that problem https://www.youtube.com/watch?v=dHzeHh-3bp4&list=LL&index=6
✅ Series Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53t6iznGWrD_QB66ZoIz2BHa
Grab the Project files and Utilities at https://unitycodemonkey.com/video.php?v=dHzeHh-3bp4
Let's create a UI Arrow Pointer that will point to a location in our world.
If you have any questions post them in the comments and I'll do my best to answer them...
and it's poinitng at me insead of the objective
i'm new to coding btw
so i think it has to do something with the ui camera if i make it bigger then it's at the edge but kinda on top
whats the best way to set up a run animation uning get key. Im unsure if run should come from walk and can go back to walk if i let go of key down. is this the best way to set this up? if (Input.GetKey(KeyCode.LeftShift)) { currentState = PlayerState.Running; _animator.SetBool("isRunning", true); } else { currentState = PlayerState.Moving; _animator.SetBool("isMoving", true); }
your code is not logical, the else condition will execute under ALL other circumstances
yh whats the best way to go from walk to run
i mean i could check if current state is walk
huh, change if you are walking and you want to run?
is the logic on the animatior wrong?
That looks ok as long as your transitions are set up correctly
Yo! Quick question. My maths are off here. I have three points A, B, C (Camera, Character, Target). I want my Camera to be exactly behind my Character while looking straight at the Target (I want a segment from A to C crossing B). How can I do that?
My idea was to take the direction from player to target, and then set the camera position as player "_player.transform.position - (distanceCameraPlayer * directionPlayerToTarget)"
But i'm not sure if it is correct
your camera position is based on player.forward while its orientation based on its position and target, not sure what "behind" means
I forgot to mention it's a FreeLook camera. Don't know if it can help
Behind means like this :
Camera Player Target
they are collinear
no, behind something usually mean -transform.forward, imagine the player looking up then if the camera is behind the player:
^
|
PT
C
back to your problem, you can construct a PT vector first, and P-some dist*PT can be the camera position
C<-- -PT*dist -----P----PT--->T
ok my bad
Like this ?
yes
Ok perfect! Thanks for the help!
Yes 👍
can you take a look at this
What are you trying to do ? An arrow behind your car that point to the cross ? (the same thing as me or not)
not behind the car , at the edge of the screen
Hey, just wondering if there's any difference between this int(Mathf.Floor(entityHeight)) and this int(entityHeight) Ignore the variable names
Like, at the top or smth like that ?
assuming entityHeight is a float value then there is no difference. casting from float to int will always round down
around the screen
i sent a tutorail for it but it's in 2D
Ok
k ty, also i realised i wrote it wrong but it deosn't matter as it solved now anyways lol
I saw, but I figured out what you meant
Ok, sorry I can't help you then I didn't start learning UI. I thought it was a problem with the direction
np
Hi. Although I am 99% confident in myself, I'd rather ask you: Using, which is indicated in gray, does this mean that it is not used in the script, and it can be safely deleted?
yes
Thanks
which topics should i study after the code beginner pathway?
probably more information than you need but you should always remove unused using statements because although the script does not use them they do create a dependency in the compiled dll
Hi, I have a problem with my Unity Code:
https://gdl.space/kemuburucu.cs
Would make me really happy if someone could help me ^^
why are you serialize the reference but not reference it directly in inspector?
SFX is a GameObject, why would you think GameObject has a PlaySound method ?
I can't drag the object because its not destroyed on load. But serialize makes no sence
didnt notice that, btw is your ide configured?
I added a PlaySound Method in the Script of my SFX GameObject
what script?
Yes, but you're trying to call a method on the GameObject itself, not the script
SFX Script
https://gdl.space/afanugukud.cs
so you need
SFXScript sfxScript = SFX.GetComponent<SFXScript>();
sfxScript.PlaySound("grinchDeath");
So i have to call it on the script?
the method is belong to your script not the gameobject
Ok, I think I know how to fix it now, thank you
probably zoomed out too much. press 'f' key with object selected
wtf thank you lol
Hi guys, I have two deferent custom classed lists and now i wanna check if they are equals or they are not, I do it like "If (list_1 == list_2)" and i don't get any error but they program always says they are not, even though their values are equal... any thoughts?
you are comparing references which, of course, will not be equal
so how can i compare the variables ? their variables i mean
by implementing your own compare method
Everything is easy, when you know what you you are doing, if you mean 'can I learn and implement this is an hour' then probably, no
this https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-8.0
and this https://learn.microsoft.com/en-us/dotnet/api/system.icomparable-1?view=net-8.0
give you all the information you need
how to add the 3rd on screen stick, apart from left and right gamepad sticks, i am using android stick but somehow not working, what am i doing wrong?
Are you trying to compare if they've got the same elements or are you trying to see if they're the same instance?
well said, thank u so much
yes elements and their variables, like u know, the name, the speed, the positions...
Yo! In term of optimization, when should I look for it ? When my project is close to the end ?
Hi everyone, I am currently making a first person shooter and would love some help with an issue that I have encountered using Raycasting to "shoot" my player with my Enemy. It is not detecting that my player has the "Player" tag even when it does and I have no idea why. I would love some help as I am obviously new to Unity and I am so so stuck.
middle to late, or when performance is so bad that something you did literally can’t work
I think good practices during development will make your game optimized enough
like, if you add a small feature that drops your FPS dramatically, you need to take care of that for that feature to be included
Ok thanks! Is there Unity specific things that I should really be careful about ? (this is really vague I know)
Debug.Log raycast hit , Debug.Log the method etc.
debugging should be first thing you learn
Ok 👍
use CompareTag whe asking for the tag, if you compare strings it wont work
I've been doing that but the value of hit is constantly returning null
show !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
gameObject.CompareTag("someTag")
That's what I have used to reference the tag but it doesn't work. I'll do the code thing so you guys can see it
It's the damagePlayer method on this paste of code
gpt code
I've done that too but it hasn't helped
exactly
AI code, without a doubt
also ur not printing hit.collider
not even gonna read it
so much wrong here
wait what no it's just the damagePlayer method that is AI because I was trying to fix it
well it made it worse then
show the error then
It's not an error it's just that the if statement for whether or not the gameObject that the Raycast collided with has the tag "Player" is never true and I don't understand why
I am working on a script to print text into a box. I am trying to add something to change the text size as it prints and i want a bool in the that i can toggle to show or hide a graph with a line in it you can adjust that will be used to determine text size. I found this(https://stackoverflow.com/questions/72732460/unity-how-to-let-my-variables-show-up-in-the-inspector-if-a-boolean-is-true-an) which would work in a normal scenario but im storing all the data in a struct array so i can have different settings for different part of the sentence. I also need help getting a graph to show in the inspector because i cant find anything on that.
tags are not the same as layers, direction looks wrong, you're not printing / debugging
first you should learn how to debug things instead of listening to AI spam generator
https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html
Ok I'm sorry it was a last resort as I've been stuck for a couple days now. Don't see why you have to be so rude when it is a beginner feed
take it as you will 🤷♂️
we do not, as a server rule, solve problems made by AI generated code
My problem wasn't AI generated that was just a couple lines that I took from AI because what I had before wasn't working at all. Wow kinda thought this discord was gonna be a bit more beginner friendly
doubt, your complete script screams 'AI generated'
Why?
we just know
It's for my A level computer science course work
We see a lot of AI generated code, we have learned to recognise it
Well not very well obviously because it's not AI generated
I used a lot of Brackey's tutorials
and a few random ones from youtube
and a bit of just me trying to figure stuff out
just because it has comments it doesn't mean its AI
liar, no one actually writes comments
I have to for my course work
thats true, but those comments doesn't even match the code
Yeah because I have to comment for my course work
wtf
I am supposed to comment everything
alright forget this lol
I told you what you should do anyway, if you want to solve your issue learn to debug or go back to ai
haha yeah...
comments look legit just because you've plastered function everywhere and not method so ill give you that
I promise you the only thing AI is the damagePlayer function and that's just because I got so fed up with it not working I wanted to see if chatGPT could fix it
whats the raycast hitting then?
why is there not a single Debug.Log statement in the whole of the script?
Because once I've sorted it I delete it
I don't need to keep seeing that something is working
I only Debug.Log stuff that I am currently looking at
true but add in some debug logs to figure out whats going wrong in the part thats broken right now?
Yeah I am doing that now. I am trying what @rich adder told me to do with the Draw line thing now
debug your raycast without the layer mask and get that hitting anything, then use the layer mask and see if that's the problem
anything with a collider^
Ok cool I'll try that now
thank you
that wont be much help if the if statement never hits hit.collider would just be null
Debug.DrawRay is the only sensible thing
is the player even on the Player layer btw?
It's tagged with "Player"?
layers are not tags
maybe u should have shown a screenshot of ur player's inspector since the very start of this question
oof
Yeah I know
in the code you call it Player
just tried with whatIsPlayer and still no such luck
Yeah I mixed up referencing tags with Layers
I'll try by referencing the layer I really hope this works
Why do I get this exception?
ArgumentException: JSON parse error: Invalid value.
public void SaveGameInfo()
{
GameInfo dataTosafe = new GameInfo();
dataTosafe.bestScore = this.bestScore;
string jsonData = JsonUtility.ToJson(dataTosafe);
File.WriteAllText(Application.persistentDataPath + "/savefile.json", jsonData);
Debug.Log("Data saved");
}
private void LoadGameInfo()
{
string path = Application.persistentDataPath + "/savefile.json";
if(File.Exists(path))
{
GameInfo gameInfo = JsonUtility.FromJson<GameInfo>(path);
this.bestScore = gameInfo.bestScore;
}
}
GameInfo class only contains one int
Your json text might be invalid or corrupted, post the contents of the file
Also for safety please concatenate file path with Path.Combine() instead of with +, it handles more cases and won't produce invalid paths
Path.Combine(Application.persistentDataPath, "savefile.json")
uh no
the issue is
youre trying to parse json from the file path
not the contents of the file
but yes
use path.combine
You need File.ReadAllText
then put that in FromJson
var jsonData = File.ReadAllText(path);
GameInfo gameInfo = JsonUtility.FromJson<GameInfo>(jsonData);```
Yeah, youre right, everyhing seems to work now, thanks!
Hi guys, I'm creating a brick breaker clone and I try to get into the observer pattern. What is the way to implement observer pattern when I have for example 50+ bricks? Do I have to subscribe to each of the bricks event? Or is there another way? Each brick has this script:
void OnCollisionEnter2D(Collision2D collisionInfo)
{
Destroy(gameObject);
BrickDestroyedEvent?.Invoke();
}
On my GameManager I subscribe to the prefab itself which does nothing, I think I have to find all of these and add a listener for each of them? It doesn't feel right to me
Subscribe in the script that Instantiates the bricks if you're doing so by script
Or you can find all the bricks by script once, and loop over them to subscribe
oh so in my BrickSpawner script i should get a reference to the GameManager and then subscribe like so?
yeah thats what i would do but it doesnt feel right to me, what if I need it in another place and there are 1000 or more objects that submit an event?
The subscriber count doesn't matter, as there's only one receiver, the game manager
One brick out of 500 notifies the manager that it has been destroyed, not the inverse
The brick can pass itself to the event in case the manager needs to know which one raised the event: Destroyed?.Invoke(this)
So for your first suggestion something like this might work?
private void SpawnBricks()
{
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Columns; j++)
{
Vector2 spawnPos = new Vector2(transform.position.x + i * (BrickPrefab.transform.localScale.x + Gap), transform.position.y - j * (BrickPrefab.transform.localScale.y + Gap));
GameObject brick = Instantiate(BrickPrefab, spawnPos, Quaternion.identity, transform);
BrickController brickC = brick.GetComponent<BrickController>();
GameManager gameM = FindObjectOfType<GameManager>();
brickC.LooseEvent += gameM.OnBrickHit;
_bricks.Add(brick);
}
}
}
Awesome that makes sense, thank you so much 🙂
cache your component in awake for game manager
should directly spawn it as BrickController instead of GameObject , save a GetComponent
BrickController brick = Instantiate(BrickPrefab, spawnPos, Quaternion.identity, transform);```
you have to change BrickPrefab to BrickController type from GameObject
I'd also rename the very abstract LooseEvent to something like in your example, Destroyed or something.
No need to specify "Event" in the name, as long as you name it as a verb in the past tense, it's directly visible that it's an event
Thank you all very much. Very useful information 
Hi, so what I want to do is make an object follow a point in space. The point in space can be thought of as a game object which is a child of the player, so when the player moves the point moves relative to the player hence moving the object to follow the player
I know how to make the follow part but how do I calculate the point in space?
Haven't you already answered this question yourself? A simple approach is to make an empty child object of the player and use its position
Yo! I have a hard time understanding the difference between Rigidbody, CharacterController and the concept of Collider. Can someone redirect me to a good video for this or explain it to me ?
I didn't find any video CharacterController vs Rigidbody that explains the difference in details
soooo many threads on this wdym
prob not videos but plenty of google results on unity asnwers/forums
As I say I wanted a video
Hi, I have just exported my first game but I have two problems, the quit button doesn't work and the menu text in unity is fine in size but when opening the executable the text is very small. If someone could help me I would appreciate it very much
well, you won't always find a video
especially for things that you can summarize in a paragraph
make sure you set correct Scale With Screen size and proper anchoring
reading hard
A collider defines the volume an object takes up. It can be a non-trigger, meaning it's an actual solid shape, or a trigger, which doesn't block objects and is only used to detect when things are overlapping.
A Rigidbody participates in the physics simulation. It can both affect and be affected by other physical objects. It's fully simulated by unity's physics system. Rigidbodies can collide with other objects if both of them have colliders.
A CharacterController isn't handled by the physics system. It's just a way to move around without going through colliders. A CharacterController includes a capsule collider.
And I also searched for threads but I don't understand what is the "best". The general answer is "rigidbody" = physic, "CharacterMovement" = simple movement (without actually using physics)
there isn't a "best"
As a programmer ur gonna have to read alot of threads / documentation, Stack Overflow, unity Threads is all essential
no such thing as "best"
which is best: apples or a power drill?
The interpretation here is correct, though.
how can i put the scale with screen size
Yes I searched for threads and I read some but they just throw basic answer with no depth
Reminds me of superliminal
on the Canvas Scaler
just start with rigidbodies
thank you
and if you come to a part where you have to ask yourself how to do something differently, then you can consider the cc
I always have a hard time making the camera follow a rigidbody Personally so i try to stick with CharacterControllers (Except in 2D)
I haven't tried to do a first-person rigidbody controller before
^^^^Thats my problem
It always jitters
Idk about a 3rd person controller which is what i think oof is doing
the old Standards assets used Rigidbody movement
Thanks. But what is the goal of the CharacterController. Why should I choose one instead of another ?
if you like to do more work
I'm sorry but no
only you can know that by trial and error
a character controller is not physically simulated
I helped you like two days ago i think?
This makes no sense
you directly tell it how to move each frame
Yes but it wasn't that helpful sorry
Not to be mean
I just have more questions
the only thing a CharacterController does is move you without going through colliders.
It was kind of you
its confusing tbh
a non-kinematic Rigidbody can be shoved around by other physics objects
if i have the executable, if i click on build it generates another executable or replace the first one?
a kinematic Rigidbody is closer to a CharacterController, since it's not affected by physics forces
You could also try a different game engine Dont ban me unity
CC is like a mix of Kinematic RB and dynamic rb (velocity part)
however, there is still a key difference: it'll still only move in physics updates
am i going far like this or no?
a CharacterController moves immediately when you ask it to.
You're on to something here, but it looks awkward right now
wtf
ik it's confusing very confusing
if i have the executable, if i click on build it generates another executable or replace the first one?
If you have five different states you can be in, you should use an enum, rather than five bool fields
as long as they're mutually exclusive
so if you can't be idle and ready and reloading all at once, you can just do this instead
i am making a musket
so many nested if statements
public enum State {
Idle,
Ready,
Reloading
}
holding both f and q key hurts my fingers
it's like four of them 🥱
too may for my taste
ik i am gonna try to change it
mind as well use && then
I presume you're trying to simulate all of the various steps of reloading a musket
yeah idle then make ready after aim, shoot, used,relaod repeat
Heyo!
Can someone tell me if it's possible to query the current lobby a user is in to get data?
Do you have examples in which one is more suitable than the other?
I would suggest writing a method that tells you if the weapon is ready to fire. It could look like this...
how do i make it pressed once
and not keep holding it
you would need to remember that you've already hit a button (or buttons)
What is pressing those buttons supposed to do?
Change how the musket is being held?
yes
and what state it's on
very important
I would have an enum for the various grips you can have, similar to what I showed here.
private Grip grip;
private bool hasPowder;
private bool hasBall;
private bool hasPanPowder;
public bool CanFire => grip == Grip.Normal && Loaded;
public bool Loaded => hasPowder && hasBall && hasPanPowder;
but how does it work?
It might be like this
wut
CanFire is a property. It runs a method when you read it.
um i think it's supposed to be like this
Debug.Log("Can I fire the gun? " + CanFire);
that will print true if grip equals Grip.Normal and Loaded is true
maybe you're unfamiliar with the syntax I used there
here's an equivalent
that was extremely obvious sorry for the idiotic question
public bool CanFire {
get {
return grip == Grip.Normal && Loaded;
}
}
You could also just make it a method, I suppose
public bool CanFire() {
return grip == Grip.Normal && Loaded;
}
Properties are nice because you use them a lot like variables
if (Loaded)
well
a CharacterController should be used if you want tight control over movement. this is appropriate for a first person shooter, for example
If I understand correctly. If I don't need realistic physics in my game it is more logical to use a CharacterController than a rigidbody because it will take less effort for the same result (better result) ?
it's inappropriate if you need the player to be heavily affected by physics
oh and should i use a get component to desactivate character controller and script?
The problem is I don't know where to draw the line of "heavily" affected by physics or not
Do you want to make your own physics or not
if you don't want to figure it out yourself, basically
What does that mean ?
You have to tell the CharacterController exactly how to move.
If you want to make the player rocket jump, you have to figure out how to make that happen yourself
you can't just use Rigidbody.AddExplosionForce
Let's say I want to make a souls like. For me CharacterController is better because the game don't have that much physics, is that right ?
probably
I'm using a character controller in my own soulslike game, yes
rigidbodies are really good for accumulative forces and high speed projectiles
And I can make everything with the characterController, no limitation? Elevators, flying platforms, health system?
a health system is completely unrelated to how the character moves
A health system has no relation to a character controller. Everything else depends on how you can integrate moving objects in regards to the character controller . . .
The other two require some work.
If you want to do more advanced character movement, consider this guy
it's a free asset that implements a much more elaborate character controller
It does a great job of handling moving platforms
but it also requires more from you than just using a default CharacterController
I'm saying that because OnControllerColliderHit is only called when the CharacterController is Moving
https://docs.unity3d.com/ScriptReference/CharacterController.OnControllerColliderHit.html
And I got a problem with that
yes, because that's used to detect when you move into an object
this has nothing to do with things hitting your collider
why would you use that for damage anyway
A CharacterController includes a capsule collider, and you can detect when this collides with things using the usual physics messages.
Oh ok, what should I use when something hit my character ?
OnTriggerEnter also works btw
So I can use OnCollisionEnter Exit etc ?
or use a raycast / physic queries
no OnCollision are for rigidbody only , thats you have OnControllerColliderHit
can always just cast upon the weapons as well if you want specific hitboxes
well,
But wouldn't that be easier with a rigidbody ?
i would not say that's correct. i will go check again to be sure, though
done it so many times i'd be surpised to be wrong on that one
id love to know though
doesn't matter your method, casting with fixed time uses the physics timestep anyway, but rigidbodies does have some extra interpolation for checking
for collisional purposes
casts/physics queries only care about colliders
you can however make your own continuous collider checking methods if for reason you're not registering the hitboxes between colliders
more likely to happen if smaller hitboxes, or quicker movements
Is CharacterController something specifics to Unity ?
so I'm partially right!
It looks like a character controller behaves like a kinematic rigidbody
wdym
So it will cause messages when it enters a trigger collider with a kinematic rigidbody
It will also...eventually cause a message when it enters a trigger collider without a rigidbody
it's inconsistent, though
afaik you dont even need rb on the trigger for CC saw ur second msg 🙂
And if a non-kinematic rigidbody hits it, collision messages can be sent
notably, not if the character controller tries to move into it
I made the capsule stop once the trigger message went off
it's weird
it notices, eventually
I think I'm relying on this behavior in one of my games. oops
thats strange mine triggers the message as soon as edges intersect
or maybe im just remembering wrong 😵💫
I think OP was asking about if OnCollisionExit would work though, that afaik doesn't work at all on CC does it ?
Kinematic rb needs a dynamic for it on other collider, so maybe if the other collider had dynamic rb it would work on cc?
both Exit methods work fine
note that this does not include you trying to move into a wall
i get the proper messages when i drop the cube on the capsule
but if the CharacterController tries to move into the wall, it just stops short as expected
and no physics messages occur
ahh so its basically like the other dynamic calls it just cause it hit Any collider, makes sense
I'm making a space invaders game to learn the engine but for some reason I cant get the collision detection right. from the tutorials I've seen I don't notice anything wrong. can I please get help thank you in advance.
{
Destroy(gameObject);
}```
did you check OnCollisionEnter2 documentation?
and trigger conditions for it?
that link will walk you through all of the ways physics messages can go wrong
Okay I'm taking a look at it now!!! thank you.
I SEE THE ISSUE I HAD TO WRITE OnTriggerEnter2D
TY GUYS
hello folks, I'm making a game that requires 5-6 on screen sticks, something like this, I have mapped 2 on left stick and right stick of gamepad, how to add other gamesticks for android ?
is this a code related question?
I tried to connect using android gamepad stick but that's not working for some reasons, what to do?
this is a code channel
somewhat yeah
I also entered in input system, this channels more experienced and active, saw someone asking raycast related question too so
the same way you added the first two sticks
But there are only 2 sticks for gamepad, if I add another as a left stick do both work?
You might need some code to "redirect" the physical joystick input to your third virtual gamepad
Unless I didn't get your question
alright so i want to make a game i got the objects and stuff im just basically bored and stopped coding pre 2021 and im trying to get back into coding after on and off things for 3 years
basically i just need help creating graphic area and also other things and advice on it
i got the player controller its a litteral bean and it had sound attached to it
im trying to get to the more advanced part and boost my coding algoritem and combine different genres into one
and also art styles
cutsences and whatnot
So I'm using the 2 joysticks as I show here for movement and view, the third is for various player skill moves, and I'd like to make 2-3 more joysticks but only 2 are working right of the bat
I've mapped triggers of animations of skill moves to the third joystick too and initiated that in the player controller and it works with right stick but as soon as i make the third stick android stick or another, it stops working
how can i get coordinates of click on button?
smth like this:
GetComponent<Button>().onClick.AddListener(() => Debug.Log(coordinates???));
im doing an enemy AI but when I start game enemy is not coming to player. its going up
can you tell me what I'm missing in this scenario dude,
#if ENABLE_INPUT_SYSTEM
public void OnMove(InputValue value)
{
MoveInput(value.Get<Vector2>());
}
public void OnLook(InputValue value)
{
if(cursorInputForLook)
{
LookInput(value.Get<Vector2>());
}
}
I've made another vector2 for other skillmoves too
Problem is the joystick scripts from input function work for gamepad but not for other sticks
Does anyone know if Localization gives any event on change? I need to recalculate the rect transform depending on the new text
You can listen to StringChanged on a LocalizedString
or use the OnUpdateString unity event on a LocalizeStringEvent, for something component-based
It's a bit confusing because I don't know whether you're referring to the physical joysticks on the gamepad, or the virtual ones on your UI
wdym by gamepad and not other sticks?
could u give me an example on that ?
I convoluted my explanation, gimme 1s
1s
these are the 4 joysticks to be present as in game flick mechanisms and I'm using onscreenstick script as a way to link my input system to them
problem is onscreenstick only covers 2 gamepad sticks as part of it's stock functionalities i think and I need more than left and right gamepad stick, I need at least 5 2d vector sticks
your issue is in the InputSystem Asset
I mean I can't link other 2d vector bindings to onscreentouch UI, like I've given zxcv as a keyboard composite and it works also if I have a onscreenstick connected to right stick of gamepad but not for other sticks available
also why do you have the clone of the same script so may times
That script links inputsystem to onscreen joysticks
as far as my understanding goes
I don't think that "On Screen Stick" components use the Actions Asset at all
Seems like they take a key binding directly
as soon as I swap left stick gamepad for android joystick it stops working, that's my only issue
unless those scripts are defining new controls for the input system to use, I wouldn't expect them to show up in the menu here
(i have never done such a thing before, so i'm not sure how that'd even work)
alright I now understand somewhat a lil bit more after reading this script, android stick it seems is controlled by the android section of the plugin, it's just not a drag and drop for other input bindings as is for gamepad and keyboard bindings
most of the youtube tutorials seem to doing with only 2 sticks since most games only require 2sticks, I'll see what I can make do of the android scripts and if I can cook something, most likely burnt toast incoming
can i somehow dedect what deleted a gamobject because a gamobject gets deleted the frame that i spawn it and i dont know why
do you have any code that calls Destroy?
Add an OnDestroy method and log something in it or attach a debugger.
yes in the object itself but i checked with debug.log but that function doesnt get called
...i'm pretty sure that runs instantly when you destroy an object, at least
rather than at the end of the frame, when the object actually gets cleaned up
how did you test that? Show code
tried it but i dont know wich script deleted it
this is where a debugger would be useful
break in OnDestroy, then step out to the culprit and look at the name in the debugger
void Update()
{
if (!IsOwner) return;
if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("Game"))
{
var player = Instantiate(playerprf);
player.GetComponent<NetworkObject>().SpawnAsPlayerObject(OwnerClientId, true);
player.GetComponent<PlayerMovement>().ch = ch;
var cam = Instantiate(camprf);
cam.GetComponent<CamaraMovement>().player = player.transform;
cam.GetComponent<CamaraMovement>().CamerHolder = player.transform.GetChild(1);
cam.GetComponent<CamaraMovement>().chatGo = GameObject.FindGameObjectWithTag("Chat");
Debug.Log("deleted gamobject");
gameObject.GetComponent<NetworkObject>().Despawn();
Destroy(gameObject);
}
}```
how do i use the debugger
private void OnDestroy()
{
Debug.Log("im dead");
}``` this funktion gets called
wdym by "my reload time just dont exist"?
it's supposed to wait 13 second before shooting again
And? What happens instead?
no cooldown i can still shoot
Ok you'd have to show your code (not just that one function, the whole script)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
all my code or just some part
The part where you call the coroutine and the part where you check isreloading would be nice for a stsrt
using UnityEngine;
public class GunSystem : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public AudioSource firedSound;
//public ParticleSystem SmokeParticle;
public int maxAmmo = 1;
private int currentAmmo = 1;
public float reloadTime = 13f;
private bool IsReloading = false;
void Start()
{
if(currentAmmo == 1)
{
currentAmmo = maxAmmo;
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();
muzzleFlash.Play();
firedSound.Play();
}
if (IsReloading)
return;
if (currentAmmo == 0)
{
StartCoroutine(Reload());
return;
}
}
void Shoot()
{
//SmokeParticle.Play();
currentAmmo--;
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
HealthSystem target = hit.transform.GetComponent<HealthSystem>();
if(target != null)
{
target.DamageEater(damage);
}
}
}
IEnumerator Reload()
{
IsReloading = true;
Debug.Log("Reloading...");
yield return new WaitForSeconds(reloadTime);
currentAmmo = maxAmmo;
IsReloading = false;
}
}```
You're not doing anything to check if you're reloading or not when you shoot
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();```
you're just shooting no matter what when you click the mouse
I would expect you to check the IsReloading variable before shooting
I would guess that this part:
if (IsReloading)
return;```
Is supposed to be BEFORE the Shoot stuff
but you put it after
make sure when you follow a tutorial that you follow it exactly
I would not put it past Brackeys to have made this mistake and silently corrected it later on haha
i used to think brackey tutorial were outdated
they are slowly being
i guess
They are also mostly garbage in my opinion
i mean yes his average video are from 2019-20
and he stopped making vid 2021
so yeah
you are right
now i am in the fun part
They are a bit outdated, but the real issue is that even when they were coming out new they were just bad and often wrong. The amount of issues people STILL make to this day because of bs from Brackeys is amazing
animation🥳
some tutorial i tried did not work so i gave up and found other like dave game developpent and fps builder
and natty
hey, so I'm doing the junior programming lesson and I'm just wondering how do I rotate an object when it's on another object?
what do you mean by "on another object"?
you can rotate objects by setting their Transform's rotation or localRotation in code, or by calling the Rotate method on the Transform.
It all depends on the nature of the rotation you want.
So I've got a plane with propellars but the propellars aren't moving when the plane moves, so the objective is to get the propellars to move when the plane is moving
the simplest thing would be to call Rotate on its Transform
obviously you'd need to do this every frame and you'd want to rotate at different speeds depending on what's going on
at a basic level something like:
propeller.transform.Rotate(0, 0, Time.deltaTime * throttle * propSpeedMultiplier);```
update
Yes in Update generally
That's where you do things that need to happen every frame
Thread
like what is propellor, do i need to reference in as a game object
public float GameObject propellors;
void update()
{
propeller.transform.Rotate(0, 0, Time.deltaTime * throttle *
propSpeedMultiplier);
}
like this?
It would be a GameObject in my example. You could and probably should also directly reference the Transform
of course throttle needs a value
what on earth is a float GameObject?
also Update needs to be capitalized
its so it can appear in the inspector so u can refrence it
float GameObject is nonsense and has nothing to do with the inspector
That's not how that works
yes i know its a rough type up
it can only be either float or GameObject. Not both. In this case it should be GameObject
You could use [SerializeField], but it'd already be exposed to the inspector since it's public right now
oh shit sorry yea is would be public GameObject sorry
and then the name so the script can read it off the inspector
im dumb I dont even need the game object
line
I spent to long if this was that simple
What do you think float means
A numeric number that has a decimal number or a floating number
Okay, and do you know what a GameObject is
Is there a way to parent an object using script?
Yes, I do, I create a line with public GameObject object; So i can add a hierarchy object to that box in the inspector
Or, to be more specific on what I want to do, I want to make it so whenever an object collides with an other, it kinda gets stuck to it in a way
parenting sounds like the easiest method
so i refer to that object
transform.parent
So, since you know what float and Game object mean, you should have been able to realize float GameObject made no sense without us having to tell you
Yea but i was over complicating the task
What's accepted for the most part: [Accessor] [Type] [Name]What you've done [Accessor] [Type] [Type] [Name]
oh so its a part of transform, thanks!
online it said its a thing in gameObject itself
unfortunately its not what i want
thanks though
gotta think now
and I can unparent using transform.parent = null; right?
!docs
This is for me
for LayerMasks does it only interact with hitboxes of that layer or does it interact with hitboxes of that layer and above
and is there a way to make rays more visible with Debug.DrawRay
Only the layers in the mask (any of them)
because this is outputting cheese when there are no objects with wallMask
show how you created wallMask
do Debug.Log($"Hit object {hit.collider.name} on layer {hit.collider.gameObject.layer}");
Can I create a method that takes a list and does stuff with it without specifying the kind of items the list may contain?
alright also is there a way to make rays more visible, theyre so small on my monitor I can hardly see them
ah got it
assigned the wrong mask in the inspector
Like a method that just takes a generic List and checks a variable on the List that all the different List do have even though they are not the same item
Yep, using generics.
public void MyFunction<T>(List<T> theList) {
foreach (T item in theList) {
// do something
}
}```
now the only question is how that object is actually getting hit by the rays because the rays visible in Debug.DrawRay do not show it getting hit
your DrawRay call might not be correct (it might not match the Raycast)
Is that T just works like... the "i" on for loops or...?
im so dumb
you need to do DrawRay(transform.position, new Vector3(....) * sizeX, Color.Green, etc..)
sizeX != 5f
T is the generic type parameter. It stads in place for whatever the type of the list is
It has nothing to do with for loops
oh wait yeah 5f is duration
the important bit is multiplying the direction by sizeX
yep I see it now
hmm but this one outputted into the console twice implying 2 of the sides hit it
it's a wall detection thing and each wall shoots out 1 raycast
and this shows it hitting as well
But then I can not call anything..., it gives a compiler error with the generic type
I really should be using a parent for all these list that share attributes for that to work right?
T does not contain a member isActive, you will need to cast it to the correct type
Generic stuff can only perform generic tasks
You could probably have T implied as the specific base type
I mean the code just lets you create List of items that can be active in the inspector and checks if X amount of them is active, I wanted to simplify it instead of making a copy pasted block of code of code for each one of them; what's the best way of doing that?
Examplecs public void MyMethod<T>(T t) where T : IMyInterface { }https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
Yeah, that's what I meant, I should have really build all of these using interfaces; I don't know if I know how to restructure all of it now without breaking everything
Wouldn't the generics just also work if you just do like public void MyMehod<InterfaceName>{} ; instead of adding a constrain or am I just wrong?
I'm sure you meant public Method(Type Name) but that wouldn't be generic
T constraint should be valid for the class as well (I'm assuming you're wanting mono behavior or game object)
Oh, no, I didn't explain myself properly; isActive is not the generic isActive that determines if a component is active or not in Unity; it is a custom Boolean that indicates if whatever it is (lever, button, target...) is in activated by the player; the Unity superclass wouldn't work
Then have it constrained as the specific class with the boolean variable/property
have you created several completely different classes that each individually have an isActive bool?
Likely they all inherit/interface a base type with that field/property
Yep, they all are diferent methods since they have to check different things to be activated; I don't really now how to nest them in a superclass now
you can define an interface, say, IActivatable, that includes the isActive property and every class which has an isActive should implement it - since they already have an isActive property, they already kind of do, you just have to add an : IActivatable to the class definition so the compiler knows what you intend
So... I just do like public class ButtonLogic : Monobehaviour, isActivable {} and remove the isActive declaration (since the superclass already declares it) and then just create a new script called isActivable that just contains a declararation for isActive and it should just work?
You'd keep your implementation
it's an interface, not a class - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface
I'd read about these before continuing - this is a perfect usecase for it and a good time to learn what they are
I did use them some time ago, not much tough so I forgot XD
Yeah, I should relearn then, thx
Hi. I am having a Unity WebGL project and my prototype works on localhost. But after I released it to my server I cant connect via websocket. I can use a java client and connect to my websocket backend but I cant connect via WebGL. Is that a certificate issue maybe? Any advice on this? I have no iptables rules, dont use CORS and nginx rerouting should work fine as the ssl certificate seems to be working with my java client. Any tips are welcome.
This is the coding channel. Maybe try asking in #🌐┃web
How do i import a package for the Quaternion and other ones
how are you trying to use Websockets from Unity in WebGL ?
not gonna work for WebGL, you need to write an Emsripten library to interface Unity with the JS Websocket code
you mean because i am not allowed to use native dot net system package classes, only the javascript implementation?
yes
but i thought nativeWebSocket impl switches to javascript in webgl?
(WebGL/HTML5 support)
no idea, never looked at it but if it does not contain a Unity .jslib it ain't gonna work
maybe this one? https://github.com/endel/NativeWebSocket/blob/master/NativeWebSocket/Assets/WebSocket/WebSocket.jslib
but to be fair it doesnt work for me so.... i thought about maybe its an issue that i have to put the full chain ssl cert pem into my app?
you using ws or wss protocol?
that library looks ok, basic but workable, check your browser developer console for errors
Export.framework.js:10 WebSocket connection to 'wss://.../..' failed: Websocket error
thats all i get
been fixing up my ui so it fits these dimensions, but my ui slots are incredibly small. is there some way to ensure that the width always matches the container?
403 in access log @languid spire but the path is correct..
make it a child of the panel, then use stretch on the rect transform and set left and right bounds to 0
not seeing anything related to stretch on rect transform, where should I be looking?
gimme a second i'll show you
cheers
hello,
what is a good place to store downloaded assets? currently I moved all my assets to /Assets/Plugins, but for some reason some of those assets get moved to the root directory /Assets when project compiles.
Plugins should only be used for code .dlls
If I want a game object to animate from whatever rotation it has (could be random) to zero, how would I set that origin value in the animator? Or do I have to script it? If I have to use a script, should I use a Coroutine? Or some other way?
I have a number of third party assets in Plugins (some of them imported themselves into that folder already)
I do not see why things would be moved.
use an empty gameObjecct as its parent, then animate the child, when you want to rotate, just rotate the parent
I could work around it by manually setting the width and height but I feel learning how to do it automatically would be more beneficial
here
"Plugins" no longer appears on the list of special folders
Mm, but in the animation it needs to know how much it should rotate the object, no?
no, when you rotate the parent, child objects will rotate with it, but animations will remain local
thanks, still isn't quite behaving right however. still incredibly small
You then need to adjust the left/top/right/bottom values.
are you sure your server is set up for the correct sub protocol?
Picking an anchor preset changes the minimum and maximum anchor values, then adjusts the other settings to keep the recttransform at the same size.
make sure the object is a child of the container
yeah it should be
what kind of sub protocol? its my first webgl project, no i am absolutely not sure 😦 but what i can say is that if i test the app with localhost in my browser it works and if i try to connect to the remote server directly in unity, it works too. only webgl on remote server doesnt connect
ah, but that won't be possible because I'm already scripting the original rotations.
So I think I will have to use a Coroutine
What's the coroutine for?
can you show me scrollview's rect transform and content and inventory slots as well?
You could always poll the progress of the animation if needed
Rotating the object from its current to the target rotation in each frame
ok, let's be clear, what behaviour do you want to achieve?
I'm assuming you're attempting to sync something relative to time with the coroutine
here ya go
set inventory slot right and left to 0
what does the right and left mean?
Let r be the rotation of an object and t its desired target rotation, I would like to smoothly transition from r to t in a set amount of seconds
since it's a stretch does that just mean essentially what the margin is?
Hello, I have this simple code here but it doesnt work.
Debug.Log("Collision"); does work, but Debug.Log("Works"); does not work. I checked in the inspector while playing the game and the script is enabled so I have no idea why this would not work
right means how much space there is between the object's right bound and the container's right bound, if you set it to 0 there will be no space. Same for left
and where are animations?
What do you mean by that
changed it in the prefab but now in the actual screen it's still the same :/
hang on, got something else to try
you asked something about animations
nbm didn't work X/
not sure where you messed it up xD. uuuuhh... show me every rect transform inside Inventory screen (included)
My original idea was to use an animation to simply create two keyframes that "automatically" change from r to t without me having to do anything, but in order for that to work I would have to tell the animation clip that r is an arbitrary value of the game object, but I only find ways to set a set constant in the animation.
So I wasn't sure if that's possible in the first place, or if I should use scripting to achieve this problem
back to square one. on the way
ok there is no need of using animations. Try this https://docs.unity3d.com/ScriptReference/Quaternion.Lerp.html
As you are getting a 403 error, than can only be issued by your server side code so I suggest you debug that code to see what exactly is causing it to respond with that error
Last one there is the prefab for the slot
i just reread my code and tried to add more debug log output for the exact error. i hope this will help. thanks for your hints so far!!!!!! a thousand thanks
@spiral narwhal even better: LeanTween https://assetstore.unity.com/packages/tools/animation/leantween-3595
Yup looks like what I need! Thanks!
But can I use a coroutine for this because I don't want to use an update method when I don't have to
use leantween
Yes, you can if you want . . .
is inventory screen a panel?
Eh, would rather avoid using custom packages that may change their licence in the future (as Unity showed :p)
Gotcha, thanks
set content's left and right to 0
Does the checkmark mean the script is enabled?
well I trust it, you can make a lot of animations and you reserve from using animation automatons
naturally, yes
moves it to the left side, so it's recognising the full container, just not filling it properly now
Well I am confused then, beacuse when I do Debug.Log(enabled) in the script it returns false
DoTween is better 😛
ok now inventory slot's rect transform should have changed, set left and right to 0 again
same as above
do you have an specific problem that involves it?
can raycasts travel inside 2d colliders?
lol, show me the transforms again
if I'm not wrong, raycasts detect the outline of the collider, if its completely inside it won't detect it
seems like it's behaving strangely
will they detect the collider if they reach the edge again?
gimme all the transforms as before please
righty ho
only edge colliders
probably, didn't spot there was a ui channel
@queen adder
will move over there if Zirok needs any more
why is inventory slot inside a canvas now?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
that's just the prefab view
let's move to that channel, we dont want to bother
so if I use a circle collider it won't work?
As I was trying to explain it I realised what I am doing is stupid and wouldnt work anyway so I gotta figure it out differently anyway
what are you trying to do
by travel inside what do you mean?
like not make it stop ?
what's that
uses to happen
yes, until the raycast reaches the edge
only with edge collider
the way you should post code here, haven't you been around enough to know?
#💻┃code-beginner message
you can also do a raycast towards the point from outside
create a raycast inside a collider from one point to another to measure the distance
if you have two points why you need raycast for distance?
check ur input manager
there are two type of ray cast, mouse projecting ray cast and object raycast which projects from the center of the object
well, I do not have the second point-
sorry, explained it badly
To say in more detail, I have a point on the edge of a circle collider, and a point outside the collider. I need to raycast from the point on the edge of the collider to the outside point, so I can find a second point on the edge of the collider. Then, I want to measure the distance between the first and second points on the collider
you can create an empty game object and make it a child of the object you have and then put the empty game object to your desired edge and add the ray cast script to it
simply create empty game object as a position for the ray cast and make it a child for the main object
you mean a point inside?
oh I don't have a problem with doing the ray cast, I am just asking if it you can raycast inside a 2d circle collider until you reach the edge - and, from what the others have said, I cannot
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformAttach : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Rigid")
{
other.transform.parent = transform;
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Rigid")
{
other.transform.parent = null;
}
}
}
I've created this code to make player stay on my moving platform, i made it move by using animator with "Animate Physics" Everything seems okay till the platform starts moving. Meaning that i cant move on it, my ability to move my player comes back after it stops. Whys that?
here is my code so far, and I would assume that it would create the point hit1 right on the edge
I mean it depends on whether transform.position is inside the collider or not. Maybe show a screenshot or diagram of where this object is and where t is and where the collider is
the light green cube is the transform.position/what the script is attached too, the green circle is the collider with the tag forest
And the collider is?
the green circle?
The green?
Ok so what are you trying to figure out exactly with the Raycast?
And which object is t?
Also you're doing a Raycast by plugging in two positions, which is wrong
That would be a Linecast
no
to measure the distance between t and the source ( the green square )
but I want the forest to multiply that distance-
What is t???
the target/the red squares
is there a way to debug and "see"/know what is modifying my player position
i checked all scripts, rigidbodies and colliders, and my player is moving down in a moment were it shouldn't, i cant find what is "making it going down"
Ok I think you're better off doing a RaycastAll here to get any interesecting forests and then just using the general mathematical formula for chord length to determine how much it overlaps the forests.
https://www.cuemath.com/geometry/Chords-of-a-circle/
@languid spire All i can see is a 403 when my GET call tries to upgrade to HTTP 1.1. And then in the next line the "websocket error" in console. Any last advice maybe?
Animator?
ok simpler question
could I make a raycast between these two squares without layer masking the 2D circle collider of the green circle?
thats all I need to know
not another solution thats gonna take another hour to research
all I need to know is if the raycast would work
Why would you need a Raycast here? It won't tell you anything
there is a animation running but its static so its not the source of the problem
And no it won't work
thanks
As mentioned it will interesect the circle immediately and give you a distance of 0
I was not getting the answer I needed so I just needed to make this hypothethical scenario
i do not understand.
please be clear and explain the behavior you want to achieve and the problem you have so we can help
right so if I make an edge collider like this it solves my problem got it
thanks for the help
So I'm trying to make a raycast to my square however it appears to not work as intended, any thoughts? I'm thinking it has something to do with the layer being set and/or the collider itself
void Update()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Debug.Log("Mouse clicked");
RaycastHit hit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Debug.Log("Object clicked: " + hit.collider.gameObject.name);
}
}
}
you can use OnMouseDown
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
I'd prefer to stick with Raycast since I'm already on this track, but thank you
it's simpler, you just tell the method what you want to do when an object is clicked and attach the script to an object with a collider
I see you have a BoxCollider2D so maybe use Physics2D.Raycast ?
Oh is that what it is?! @languid spire
maybe, I dont do 2D but it seems logical
I am trying to rotate an object towards another object, but the only way i can think to do that is through quaternion.rotate, which means i have to call it every single time in the update() method. is there any other way to cause an object to fully rotate towards the intended target?
(so that i can put it all in one function and only have to call it once)
You can make it feel like you're only doing it once by using a coroutine, perhaps.
A coroutine lets you write a method that "pauses" until it gets resumed by Unity
on the next frame, by default
so if i write a co routine with the quaternion. rotateTowards inside it
Right. The coroutine would repeatedly rotate a little bit towards the target
it could quit once the angle difference is almost zero
exactly zero is something I'm not sure you should test for here
Quaternion.Angle(a,b) measures the angle between a and b
i see
i see i see
its for a rubiks cube tho, basically what i am doing to rotate the top layer is making a new empty gameObject, setting it to the middle piece on the top's position, and rotating the empty gameObject 90 degrees, and then making all other top layer pieces children of the middle top piece and rotating towards the empty game object
if that makes sense
Physics2D.GetRayIntersection is the appropriate function for this
sticking things onto an empty and manipulating the empty can be a lot easier than doing the math yourself
yeah because they need to be unchilded afterwards since cubes can be parts of different faces
that is another problem i am having
how can i make it so that when i set their parent to the middle piece of that face, then rotate, and then unchild them, so that they keep the position and rotation they are in
come across some tutorials that talk about a new input system that you get via a package, would you say it's best to use that moving forward as someone starting out?
no, it's much harder to start with if you're a beginner
stick with the "old" system for now until you get better as a programmer
alrighty then, I'll take your word for it
I've figured out the aiming of my characters blaster, but for some reason he rotates based on his edge and not his center
Hey people 🙂 I know this is just straight up maths, but do any of you know how to get the angle of a in Unity c#?
I have a two variables available: distance and height, but I've been stumbling a bit on getting Unity to return the angle itself
Does anyone here know the correct method? 😊
How do I set the sprites center for rotating
simply cause I'm watching a tutorial on implementing joystick movement and none of them cover anything without the new input system
This is just trigonometry, not really a unity question
It's unclear what "distance" and "height" are in this image
maybe label them?
Sohcahtoa
Soh Cah Toa!
Adjacent / Opposite
Sin cosine tangent
So tangent(opposite / adjacent)
Do note that in Unity trigonometric functions take in and return values in radians, that can be converted to degrees using the Mathf.Rag2Deg constant
Yep
in fact I straight up can't find any at all for the old input system :(
in this case I need an on screen joystick like mobile games do. I've been using my keyboard so far to test but I'll need to put the thing on an android app for the project but none of the content I've found explains that without the new input system
for an on screen joystick the new system will indeed be much easier
since it's a built in feature of it
in the old system you'd have to build that yourself from basic UI elements and code
Oh nice, I'm trying to learn how to set up a physical joystick lol
but you'll have to learn the basics of the new input system for that
yeah, I think for the time being I'll go and use it. Player movement never needs to be complicated for this task as it's only a uni project that doesn't have a focus on the player controller, it's just movement on a flat plane. But for my own projects moving forward I'll stick to the old one
How do I make my sprite character rotate at its center?
In code or in editor?
In code
transform.eulerAngles = new(0f, 0f, angle);
The sprite is rotating on its right side making his turning look funny
is the sprite centred to the gameobject
The sprite is the game object
Can you send a screenshot in editor of the sprite with the move handle on the pivot setting
Like the sprite sort point in the inspector?
scene view
Pivot / Local to see where it'll rotate around
Does the same sadly
Thanks for the trig help everyone 😛
If anyone is curious, the way to get the angle value is as follows:
Angle = Mathf.Rad2Deg*Mathf.Atan(Opposite/Adjacent);
its most likely an issue with the sprite, like it having whitespace on the right side
that doesnt track
how are you rotating it in code?
transform.Rotate(new Vector3(0, 0, Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));
Arrows seem pretty centered in that screenshot. Sprite is 1.5 square wide, and the arrow looks like it falls at around 0.75 squares