#💻┃code-beginner
1 messages · Page 80 of 1
I said before I haven't been in this sort of area much 😅
this method OnTriggerEnter is giving you a Collider2D of whatever was hit
So what object do you want to check the tag of
The player
And how do you intend to reference the player
With it's collider?
Where are you getting the collider from
The player Gameobject?
So you want to directly reference it? Drag in an object from the inspector?
Seems like it
So I need to serialize it?
So, if you have a direct reference to the player, what is the purpose of checking the tag
You would know it's the player then
If there's more players?
So then how do you intend to identify the player
With a tag
The playermodel(s)?
I'm not asking what you're hoping to find. I'm asking what object you're checking
I feel so stupid in this conversation right now 
why is there a multiple page long conversation on something that can be solved by saying four words 
What is the thing you're trying to check the tag of to see if it's player
The collider?
Correct. And what is the name of the variable that holds the collider
Collider2D?
OnCollisionEnter or OnTriggerEnter?
Isn't that something that holds a value? If so ignore the last message
So what is the name of the variable that holds the collider
its a Collider2D why would be a string or float
What
I said that earlier!!
so whats the name of it?
in the code you're looking at
At no point have you said the name of the variable
I'm not asking for the type
I thought you meant the variable itself 
I do mean the variable itself
What is it called
The name of the variable
Not the type
Not what function it's in
The name
This white text?
thats a variable name, but not one in the function is it
Where is this
This isn't in the code you've sent
Where are you looking
Why did you make a new variable
Use the one you already have
That comes from the function
The parameter to the function is the collider you have collided with
@thin sedge variables in a function( ) work exactly the same naming them outside of a function
Type name
So I need to compare the Collider2D "collision" thing?
instead of the "other" thing?
🎊
How do I get the reference from my Ball.cs script?
[Header("Timer UI")]
public GameObject timerText;
private float TimedText;
public void TimerText()
{
timerText.GetComponent<TextMeshProUGUI>().text = TimedText.ToString();
}
is working now?
you mean get reference to your ball script from here ?
Yeah
Yes but it doesn't reset the bool after the animation is played
you need a way to reset it
code doesn't do things magically by itself lol
only when it gos awry 👿
same way you made the other references before [SerializeField] private Ball ball
Thread takes up less space :)
i do not know why my character is not jumping. No matter what i do. I already checked my input settings. It just doesn't work. Anybody got an idea?
serializefield is only for private fields btw
public fields are already serialized in inspector
Oh right
So how do I take that value from the inspector and dispaly it to the text field I created?
you have to expose the current timer if you want to display that
not the TargetTime
since thats the starttime
did u not debug what I asked earlier..
📃 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.
ok so what is the result
screenshot the whole console window in playmode
well then there you go
answer shall always be revealed to you debugging
look at your jump condition again
if (Input.GetButtonDown("Jump") && isGrounded)
do you see whats wrong?
alright
should i use visual studio code for coding c# in unity? im a beginner which one is the best to use?
use whatever you want
best tool for the job is always 
is catching up though, maybe in a few years
i like the colored brackets in vscode tho
how do i turn it on?
It made my rainbow brackets useless
i tried assigning it to spacebar, it didn't work. i really do not know.
i tried searching for any possible solutions.
i see the setting i think but it's not doing it
bro what
what part of it didn't you notice the bool
isGrounded is never tru myguy
you can't jump
sorry i really do not know.
well try to understand what you're copying lol
that aint it
forgot how to enable it tbh
mine was just on
see if Viasfora still works
the debug log is telling you that isGrounded is false. Meaning you need to go find out why it is false if you actually are grounded
How could I write a command that would raycast between two objects and report if it intersects with any collider other than the target object?
yo Im having some issues with the new input system where i will look around for a while then suddenly it feels like i miss a frame and my character is looking way further thant it should be or just straight up looking upwards for some reason```private void Update()
{
//looking (camera rotation)
float mouseX = playerInputActions.CameraLook.MouseX.ReadValue<float>() * rotateSpeed * Time.deltaTime;
float mouseY = playerInputActions.CameraLook.MouseY.ReadValue<float>() * rotateSpeed * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cameraHolder.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
transform.Rotate(Vector3.up * mouseX);
}```
Call Physics2D.Raycast, cast from point A to point B. This gives you a list/array of RaycastHit2D. Go through the list and ignore anything that is one of the two objects
oh okay thanks
Multiplying mouse input by DeltaTime is incorrect
there is Raycast, RaycastAll, and RaycastAllNonAlloc
pick the one that is best for you
Raycast just gives one hit, but is simple if you can filter out the two objects by layer in a contact filter.
RaycastAll gives you a whole array to sift through.
RaycastAllNonAlloc gives you a whole list/array, but you can keep the list/array as a variable to avoid repeatedly allocating/deallocating. If you are going to call this a lot.
I think it is a bit confusing.
+= implies he wants to parse mouse position as angular velocity, so * deltaTime is correct.
But the parsing mouse position as velocity is wacky.
i think the math here is just not correct. He would need to figure out his units
thanks
shouldnt I use a layer mask though?
you didn’t mention if the two objects have a different/same layer to what you are trying to detect, so I gave you all the options
oh okay
if A, B and C all have the same layer, then you can’t call Raycast from A to B without hitting A and B by default.
I believe mouse position has units of pixels (it is in screen space).
RotationSpeed i assume has units of degrees per pixel (which would be wrong. rotation would change based on screen resolution).
can you invert layermask?
It's definitely incorrect here. Mouse delta should never be multiplied by DeltaTime. it's not a velocity it's being used directly to rotate a transform
try ~. This does a bitwise inversion
this guy needs to convert from mouse space to something normalized/dimensionless. Probably needs to divide mouse pos by screen size or something first. Just get that in a 0-1 or -1-1 range
then he can multiply by his rotation speed, which would have units of degrees/second, I assume
I’d first get mouse position into a -1 to 1 scale. Then multiply it by rotationSpeed (angular velocity in degrees per second) times deltaTime. This would output a value in degrees, which is what he wants to make a quaternion based on euler angles.
his main mistake here is not converting Mouse position from screen space.
i found it
does that help?
whats the problem here now?
ah nice..of course it would be there lol
read the error
most likely targets is not the same type as your script
you probably need to add the hit.whatever instead of this
what is the type for targets ?
I do not want to add the thing the collider hits too the list
Guys, sorry for asking for the 99th time but I want the definitive answer on how to make an object carrying system like half life 2? (They had already told me this before but I lost the message)
so what do you want to do with this script
this is the last time I will ask that
I want add the current entry in the foreach loop to the list
transform
alright, so do you know which one is the individual transform
from the loop
a.position
an invisible gameobject in front of the player that is parented to the player. Any object that gets picked up will be parented to that invisible object and put to the same position.
oh,thanks
oh I
somehow didn't realize that- I assume just having it be a will be okay?
or empty gameobject
yea
thanks
although name it something better than a
lol
enemy would've made more sense in this context
Make sure that there are no compile errors and that the file name and class name match.
they all match and i dont see any compile errors
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
public class CreateAndJoinRooms : MonoBehaviourPunCallbacks
{
public InputField createInput;
public InputField joinInput;
public void CreateRoom()
{
PhotonNetwork.CreateRoom(createInput.text);
}
public void JoinRoom()
{
PhotonNetwork.JoinRoom(joinInput.text);
}
public override void OnJoinedRoom()
{
PhotonNetwork.LoadLevel("MultiPlayer");
}
}
thats my code
Show your console first
Clear errors first, then see what's still around
when i clear them nothing new shows up do i gotta run the game first?
What is the file name of this script
CreateAndJoinRooms
Show a screenshot of the file in your project window
Try restarting the editor
works now thanks
why cant i drag my input field into the input field thing
public InputField createInput;
i have 2 of them
Is it an input field or a TMP InputField
Any idea how come my pen isn't logging to the console?
is the component attached to an active object in the scene?
Oh weird I thought you needed to do that but in the tutorial he doesn't do that
It's logging an unusual name though, this is fairly common wacom
how can I have an If statement have two conditions?
I got two code related questions to some UI elements.
1: I'm running into an issue where if I mouse over a button inside of a ScrollRect, then, I can no longer use the mousewheel to scroll through the scrollrect is there a code related fix for this? Or is it a Unity Bug? It seems really strange.
2: Does anyone have anything that would support controllers inside of a ScrollRect? It seems very strange of Unity to not support Controller for this...
Can something like this be simplified?
public CharacterController CharacterController { get; private set; }
yikes
- just modify the scrollValue when moving the controller stick
That doesn't handle selections though. Just scrolling.
but wdym supporting controllers in scroll rects
dunno about point number 1, but for point number 2 if you are using the InputSystem then it's just a matter of you setting up your actions the way you want
- Select an object in the scroll rect.
- Move it down
- As you move it down it will select objects out of view of the scroll rect.
about no.1 scroll rect won't be detected if you have mouse over different UI element
- likely it could be a default feature that you may not want to scroll when your interacting with Selectables like buttons, sliders, dropdowns, etc, you could probably toggle the "raycastTarget" value of the button so the event system ignores it, I think there may be another way but cant think of what it may be atm
you won't be able to click the button if you do so
Yeah, both options aren't "Normal" behaviour for a Scroll Rect in the real world.
True, but if the goal is to not have scrolling stopped by hovering over the button, it coul work, when scrolling stops enable it again
Working on UI sliders that I want to stop moving when the total value is 508 or greater and Im having an absolute nightmare when I set the value to say 507 and click the far right of the slider to give it a value much higher than 508 any help is greatly appreciated
What????
Mouse over the channels on the left and use your mouse wheel. If you're over a channel, it doesn't stop you from Scrolling. Lol
just clamp it?
if(sliderValues >= 508)
{
sliderValues = 508;
return;
}
Clamp how exactly?
Mathf.Clamp the sliderValues
Sorry im not sure I follow
sliderValues is just a tally of the sliders
if (sliderValues >= 508)
{
// If total value is 508 or greater, set all sliders to their maximum allowed values
foreach (Slider slider in evSliders)
{
slider.value = Mathf.Round(slider.value / 4.0f) * 4.0f;
}
return;
}
or just add this
The total value of each slider is 252 you have to achieve 508 across multiple sliders
So the sum of all slider values must not exceed 508 is what you're asking?
Yes
so if you have 2 sliders, one is at 500 let's say
Sorry my brain is a bit fried I think what Xaxup just said might work let me test it
the second one can't exceed 8?
Exactly
having a problem where my jump function is not doing anyting despite it being called, and also my player falls super slow for some reason i canot figure out why. here is the code https://pastebin.com/dGDNMF2c
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.
In the code I linked that works fine the problem is that if I set one slider to say 507 I can still increase the next slider to say 507 too the first time I move it
where do you call the Jump function
Im checking its below 508 but I think I need to track the increase im just not sure how
Creating particles on a specific surface when a raycast passes through
jump is being called from a seperate script managing my input system stuff but its not the problem, if i add a debug.log it tells me its being called but the code just isnt doing anything
Huh... I just tried to reproduce your scenario with a default scroll view and some buttons in the "content" and it seems scrolling while hovering (or selecting/having a button "focused") is default functionality, does the scroll stopping behavior happen for you in a blank scene with just a Canvas (and its accompanying EventSystem)?
Every time you call SetMovement you overwrite the velocity
oh so its overwriting not just the x and z velocity but y too?
As long as you both check that the sum doesn't exceed 508 and correct the slider in the same frame, you won't see the difference.
You'd need a way to know which slider was just interacted with, so you can "clamp" it. Sum all the sliders except the one you just touched. If sum + sliderYouTouched.value > 508 then set value to 508 - sum. There might need to do a - 1 or + 1 somewhere to land on the 508 after the subtraction
Yup. I'm also on a older version of Unity, so, it could possibly be related to that.
Strange, which version? I have an old project in 2018.3 I tested and seems mostly the same as newer versions
how would i make it so that i overwrite just the x and z velocity?
Ahhh yeah that makes a lot of sense, can I use pointer.EventData to get the slider I just touched? Not sure what the best way to do that would be
Yeah that would be a way to do it
Holdup. Just figured it out. When you said blank scene I just copied over to a blank scene and used the same buttons I already had. However, they have a Event Trigger on them. Having that Event Trigger on them, is what causes it to stop.
Oh, interesting, glad you found the cause of the problem at least
Yeah I'm just not sure how to fix that though...
I was using that to trigger mouse over/selection popups.
Shame the OnValueChanged event of the slider (whatever it's named now) doesn't include which slider sent the event, just the new value.
or you can bind it from the code and do an ugly slider.OnValueChanged += (val) => SomeFunction(slider, val); and repeat that for each slider but it's dirty
Well a Button already inherits from Selectable which allows that functionality, you could either make a script that inherits from Button to access that functionality too, or maybe try using IPointerHandlers like IPointerEnterHandler, there is one for Exit, Click, Drag, etc as well
That would save me a headache if it was the case if you recommend getting the eventData that's the way ill do it. Thanks so much for your help!
I guess that's the easiest solution, and if it works it works
Haha I haven't a clue how else id do it anyway so heres to hoping it works
await AuthenticationService.Instance.SignInWithUnityAsync();
I need help with this method. It requires a token but I do not know where to get it from and using AuthenticationService.Instance.PlayerId results in an error
Here is my code:
AuthenticationService.Instance.SignedIn += OnSignedIn;
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInWithUnityAsync(AuthenticationService.Instance.PlayerId);
How do you get over the fear of breaking things in code?
By getting good at fixing them
lol
you cannot break things in code, there is always Ctrl+Z
version control and commiting often
using git is super easy to pickup these days now that all the good GUI's that exist, i use github desktop. Take a day to just experiment with it and how it works, and save yourself the fear of breaking things. If you arent using version control then you are always running the risk that something corrupts and you lose months of work
Also apparently unity has its own free version control thing now
You can enable it with a "link" button in the unity hub
On the left side of your project name
unity has had some version control things for awhile from what ive seen online, but really you're better off just using git
Yea ig so. It dosnt have alot of things that git has. For eg it dosnt have anything like gitignore. It saves every single .meta file in your project
Git is pretty much the only tool you'll see used in every other aspect of CS
if you are not commiting .metas to git you are in trouble
Why?
because all your scripts would be unkown or missing
where do you think references between objects are held?
Wont unity just auto generate them if any files are imported into a project?
hence why if you move files in project from outside unity without moving the meta that goes with it unity takes a shit
ha, ha, you wish
I thought they were only useful when you moved a file and so they wont be importent when uploading to git
don't think, know
i mean unity will autogenerate them if they arent there, but you're gonna have a bad time if u delete them all
Well yeah, because it's supposed to
It'll auto-generate them... with no data, meaning all your references are now gone
I have a player that is using the new Input System (not new now but hey) and all I want is the player to move left and right and up and down from a top/down view. Code here:
Vector3 playerPosition = Vector3.zero;
Vector2 _move;
public float speed = 2;
private void OnEnable()
{
controls.Enable();
}
private void OnDisable()
{
controls.Disable();
}
void Awake()
{
controls = new PlayerControls();
controls.Player.Move.performed += ctx => _move = ctx.ReadValue<Vector2>();
}
void Update()
{
Debug.Log(_move.x + ", " + _move.y);
transform.Translate(speed * Time.deltaTime * new Vector3(_move.y, this.transform.position.x, _move.x), Space.Self );
}```
Produces this movement...
Which is plain wierd. Left/Right on keyboard is -1,0/1,0 in _move and Up/Down produces 0,-1/0,1 in _move...
Can anyone explain why it goes crazy like this?
It seems strange to use your x position as the Y value of your movement speed
Turns out transform.Translate(speed * Time.deltaTime * new Vector3(_move.y, _move.x, 0.0f), Space.Self ); works nicely!
@polar acorn that's what I thought, and it turns out we're both right
Yeah, seems like your player's forward direction is actually its right direction
@verbal dome perculiar- something from blender maybe?
You would need to fix it in blender, yes
The model's forward direction should be Y forward in blender
And you need to look up the correct settings when exporting from blender to unity, they use different coordinate systems
Is it possible to create presets that are saved for multiple projects? Because I almost never find myself in the need of creating animations with loop time set to true, always to false.
Kind of like overriding Unity settings
everything in project settings and preferences is saved to a file that you can copy to new projects but unity in general is not a tool where you have default settings for every toggle and value on each component, its more like a framework on top of which you build your own tools that would then optionally give you this kind of preset. Nevertheless in some areas, like say asset import, you get the option to save presets. but nothing like you describe there.
does anyone know how to address the diagonal idle direction problem in top down 8 way movement?
basically, the player would have to simultaneously let go of the 2 cardinal directions making up the diagonal direction to get a diagonal idle direction, so what's the simplest logical answer to this problem?
what is the difference between the physics material being in the rigidbody or the box collider? it appears to have the same affect in my PONG game
not a code question, but i'm pretty sure that the difference is that on the collider it only affects that one collider but on the RB it affects all of the RB's colliders
Not sure what you mean by that
WDYM by affects all of the RB's colliders?
I know best practice is to put it in the Rigidbody2D since that's where physics are generally being applied but like I said in this simple case if I put it in BoxCollider2D it produces the same effect
every collider that is part of the rigidbody. in your case that is just the one on the same gameobject
child colliders of a rigidbody become part of the rigidbody's compound collider
Could you put it in simpler terms? I'm not quite comprehending
I guess the question is related to PONG how are they producing the same desired effect?
since you only have a single collider that is part of your rigidbody's compound collider it shouldn't make a difference which you apply it to
Huh? Player paddles have Box Colliders too
that's a separate collider obviously
Are they part of the same rigidbody
@polar acorn wdym
I mean what I said
Multiple colliders can be part of the same rigidbody
Are yours
Not that I'm aware of
Then there's no difference between setting the material on the collider or rigidbody
the obvious answer is no, they are not part of the same rigidbody because they are on completely separate objects
What's an instance of PONG where I would want to specifically set it to RigidBody2D and not BoxCollider2D?
And the other way around
why are you so hung up on pong having any relation to the question you've asked?
As stated, unless you have multiple colliders on the same rigidbody, there is no difference
@slender nymph it makes it easier to understand
the physics material will apply to either the single collider it is assigned to or every collider that is part of the rigidbody if it was assigned to a rigidbody instead of a specific collider
@polar acorn when would you have multiple colliders on the same rigidbody?
When you want a rigidbody to have multiple colliders
then the answer is it makes no fucking difference for the reasons already provided
Alright I think I'm getting it
Basically unless you have an instance where there are multiple colliders on the same rigidbody you can apply your physics material to either/or BoxCollider or RigidBody
it also helps reading the docs
https://docs.unity3d.com/ScriptReference/Rigidbody2D-sharedMaterial.html
The PhysicsMaterial2D that is applied to all Collider2D attached to this Rigidbody2D.
The PhysicsMaterial2D specified here is applied to all attached Collider2D unless the Collider2D specify their own PhysicsMaterial2D in Collider2D.sharedMaterial. If no Collider2D.sharedMaterial or Rigidbody2D.sharedMaterial is specified then the global PhysicsMaterial2D is used.
I'll give it a read, thank you
when working with coroutines can you put something after the while loop to have that thing happen when the while loop is over?
like so
yes, you can put what ever you want/need to. just try it out and check . . .
Unless you yield break, destroy the object running the coroutine, StopAllCoroutines(), or StopCoroutine(cachedCoroutine), it will run all code just like normal
FixedUpdate will run at the same speed doesn't matter if a person has 2 or 200fps right?
Fixed Update will occur the correct amount of time per second regardless of how many seconds have passed
so, framerate doesn't affect it?
What do you mean by frame rate doesn't affect it? Can you give an example?
Update is linked to framerate, FixedUpdate just happens every couple of milliseconds
doesn't it?
If you acquired some delay of say ten seconds.. The Fixed Update loop will forcefully interpolate all of the lost frames.
so it runs on it's own time?
If the main thread is occupied, it can't do the FixedUpdate.
It will run as CLOSE to the physics rate as possible (50 times per second by default). This means it could even run twice per Update if needed, or once every other
It may not be spot on, but as Dalphat said, it will interpolate it
They are both dependent on frame but fixed update will interpolate lost frames
so it's affected, but it has measures to make up for it?
The life cycle link I sent should have shown fixed update looping in the physics section until it has met it's accountable frames. It basically plays catch-up.
so if the framerate is lower it will happen like 2 or three times in between frames
It can also not have occurred at all per frame if you've got more frames than what the physics frames were set to
If you're getting less than 50 frames per second, it'll buffer extra calls to fixed update. If you're making more than 50 frames per second, there may be no physics call on certain frames.
alright i finally got that
thx dude
https://docs.unity3d.com/ScriptReference/Time-timeScale.html
Note that changing the timeScale only takes effect on the following frames. How often MonoBehaviour.FixedUpdate is executed per frame depends on the timeScale.
!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.
Hey guys,
I am trying to understand and follow some stuff I found to save and load the game in a simple way, as for what I need is just a few information. When I have the button save or load to appear, the game is under cs Time.timeScale = 0;
Here I have 3 classes.
SaveSystem: https://paste.ofcode.org/NJJgpWpb7g9dxf5wMWQKFR
PlayerData: https://paste.ofcode.org/UvGhGSreUqLfATYqAbCpQ
Player: https://paste.ofcode.org/qcqkvy9JJkAkrvmpeRREZ8
It is not working and seems to be all good. any insights? Thank you!
What exactly is not working and what steps did you take to debug it?
I put some debug logs to see if the i was getting into the SaveGame and LoadGame methods inside the SaveSystem, and also to see if the data was being fetched etc.. all looks fine.. when I start the game, there is a intro screen where I have load.. and inside the game while it is running when I use ESC the game pause with Time.timeScale = 0; and I click the button save. Stop to play the game.. play again hit loading and thigs doesnt change
I don't see any logs in the code you provided(aside from one when file is not found).
True, because after I tested I deleted it
What I do to test is lose some HP
and save
close the game, open again, hit LOAD and nothing happens my hp should be instead of 30 should be 28
You should keep the debugs when you ask for help. It makes it easier to see what you have attempted.
No problem: https://paste.ofcode.org/xSja8GVKGTtLGF57X3mUNk
There is a slight chance the issue is due to the binary formatter being obsolete.
Did you check the file that is getting saved? Does it have any contents?
Are there any errors in the console during saving/loading?
Not sure where is this saving, I will look for it: cs string path = Application.persistentDataPath + "/player.save";
no
You can print it.
Open the console and take a proper screenshot. Do you always check for errors like that?
Oh yes sorry how is the correct way?
You mean like that?
I used like that: cs string fileContents = File.ReadAllText(path); Debug.Log("Path: " + fileContents);
unrelated , but do avoid BinaryFormatter btw
BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-8.0
ok so which other method you advice me to use as a save?
just json is fine
Ohh ok, got it, thank you
That's not what I recommend but ok.
For binary there is a binary writer.
Though, I feel like the issue is unrelated to it being obsolete(I don't think it is in the dot net version that unity uses).
yeah def unrelated was just saying prob not even needed
https://youtu.be/Q0_xreJMldM?si=ijvNzPufNrkcr7TY
Maybe you can peep this, there is no explanation but I go through it very quickly
hmm ok, will try the json method. Thank u guys
you're already saving json format no need to just use formatter
btw what was the result of this log ? the path was prob wrong?
same error as the one before, some violation stuff
hahaha
I wonder if you put that line inside the stream block...
You tried writealltext already ?
PlayerData playerData = new PlayerData(player);
var stringData = JsonUtility.ToJson(playerData);
File.WriteAllText(path, stringData);```
@solemn fractal
Guys, how can I generate a raycast in front of an object and have the line also point in front as if it were the player's camera? here part of the specified code:
WIll try, thank you!
raycastOrigin = objectHolder.transform.position;
raycastDirection = objectHolder.transform.forward;
raycastLength = 3f;
Debug.DrawRay(raycastOrigin, raycastDirection, Color.green, 3);
}
looks fine
do note that a ray coming directly from the camera in the direction the camera is facing is not going to be visible from that camera
it will be a dimensionless point from the camera's perspective
Yes but I want to see it from the perspective of the scene when I pause the game
to make it the correct length it should be Debug.DrawRay(raycastOrigin, raycastDirection * raycastLength, Color.green, 3); though
what you have will work fine, what's wrong with it?
ahh duration xd
Did you turn gizmos on?
im going to check,maybe is this
Do note you're only drawing this once in Start
if the object moves after the start of the game, this won't be that helpful
ahhhh ahahaha
zhank you
nahhhhh (the green line is my raycast)
And if you're wondering, the object holder is in front of the player's camera as if it were a raycast
Oh!! I know exactly why you were getting this
i just looked at your code again lol idk how i missed this
is there a way to reliably sync a texture's offset speed with an object's transform speed?
What?
pretty sure that error is because you're trying to access the same file twice at same time
why if i click one time in the btton?
might be stream never cleaned properly
They added that line later for debugging. While it most likely is the cause of the error, it's probably unrelated to the initial issue.
But I am closing it
ohh
They're talking about the read all text line
ops spoiled myself with using statements now 😅
you got it working now though right ? @solemn fractal
Unfortunatelly not yet, i will need to sleep now, working from the office next 2 weeks, having few time during night to continue my mini game. Took some notes and will try more tomorrow and will let u guys know. thank you !!
np! gl. if you need it , your entire method can just be this and should work 🙂
public static void SavePlayer(Player player)
{
string path = Application.persistentDataPath + "/player.save";
Debug.Log(path);
PlayerData playerData = new(player);
var stringData = JsonUtility.ToJson(playerData);
File.WriteAllText(path, stringData);
Debug.Log("saved file to: " + path);
}```
Is there a better way to detect multiple collision without using tag?
I have a list of sounds, like 1 heal folder have 40 heal soundeffects, what's the best way to get a random healing sound? I was thinking of resources, or AudioClip[] HealingSounds, dunno what is better and may there be any better way?
Use Physics.Overlaps
I'm not a professional but you can put it in a list and make a random function that selects number between 1 and the amount in the list
if your game is 3d, use overlapsphere
Is 2d
yea, i can make that implementation, i was asking for a better way since im always scred of making bigg collection of arrays
since it can lag the editor while open
Oh ok
too bad you aren't on 2023 since it has the convenient Random Audio Container
but just a scriptable object that has the array and a method to pick a random one would be fine. then anything that needs to play one of the sounds can reference the SO
that's probably better yes, I dont even have to make a global library that grabs an audio
I wanna be able to make triggers-to-spawnpoints like in here, but I cannot find the right guide for it
wdym like a scene swtich? what exactly you're struggling with ?
so im making my game have multiplayer and this is my script that does the players animations and the animation is messed up for multiplayer it doesnt sync and when one person does it both do
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerMovement : NetworkBehaviour
{
public CharacterController2D controller;
public Animator animator;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
public float jumpcounter = 0f;
public CharacterController2D charactercontroller2D;
// Update is called once per frame
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (Input.GetButtonDown("Jump"))
{
if (jumpcounter < 2)
{
jump = true;
jumpcounter++;
if (jumpcounter == 1)
{
animator.SetBool("IsJumping", true);
}
if (jumpcounter == 2)
{
animator.SetBool("IsJumping", false);
animator.SetBool("IsDoubleJumping", true);
}
}
}
if (Input.GetButtonDown("Crouch"))
{
crouch = true;
}
else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}
if (Input.GetButtonDown("Sprint"))
{
runSpeed = runSpeed * 2;
}
else if (Input.GetButtonUp("Sprint"))
{
runSpeed = runSpeed / 2;
}
}
public void OnLanding ()
{
animator.SetBool("IsJumping", false);
animator.SetBool("IsDoubleJumping", false);
}
void FixedUpdate()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
if (charactercontroller2D.m_Grounded == true) {
jumpcounter = 0;
}
}
}
what are you having a problem with? you'd place a collider and mark it trigger . . .
also probably to early for you to make a network game just my 2c
try and past your !code so it doesn't take up too much space in the chat . . .
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry mb will do that next time
Yeye like a scene switch, specifically having trouble with connecting it to a spawn, I'd like to not have the player just spawn in the middle of the scene
you need a script that starts when the scene is loaded with a reference to the spawn point. spawn your player at that spawn position . . .
well if you have a certain Spawn point to go to give it a tag / script to look for ?
Should make an effort to read the documentation for netcode because you're not going to get far without it
you wanted pain.. welcome to pain
Why do we have to type the parameter names of CreateAssetMenu btw? The suggestions doesnt even show after typing ,
For SO's
you mean this?
yea
I'm having a tunnel vision right now... Why is my function not working when I'm ticking "is clicked" on runtime 
where are you calling collectPlans
because you're specifically checking that it's false (i.e. NOT ticked)
if (!isClicked)
basically what I'm trying to do is to follow this: https://youtu.be/cLzG1HDcM4s?si=iXZL7hf_fXq2DEQE&t=63 while making subtile changes like instead of doing an animation i want to unload my object
Interacting with GameObjects within your scenes is a core tenet to game development within the Unity Engine. I wanted to engineer a system that would show off Unity Events, while also being generic enough to slap on to any of your objects and wire up quickly.
Admittedly there are many ways to improve upon the basics I show in the video (as well...
well - it doesn't matter much what you're doing - the answer is you're checking if that variable is false before executing any of that code.
From my understanding, it's because those are setters. Not optional constructor parameters.
yea someone explained they're attribute thingies and not named params

Not sure if it's possible in C# 9. But it's pretty similar to constructing new objects.
new MyObject() //these parenthesis is optional if you don't use a paramed constructor.
{
ThisGetter = my_value,
TTheOtherGetter = my_otherValue
};
The compiler will also recommend doing this by default. And if the setter is an init, you can only set it under those curly brackets.
where in there talks about animation because i have the rest setup thats really all i need to know
The NetworkAnimator component provides you with a fundamental example of how to synchronize animations during a network session. Animation states are synchronized with players joining an existing network session and any client already connected before the animation state changing.
you can search in the documents
so if im reading this right all i ahev to do for animations to sync is do instead of animator.SetTrigger("Jump"); i do networkAnimator.SetTrigger("Jump");
I am about to release my game for internal testing.
With these 3 error messages is it just saying now that I just need to upload my game to the Play Store Console for Internal Testing and this is all I have left to do, and for the warnings, in my game there is no ads so the ads message does not apply to me right?
Also my game is 99cents to play for all 68 zombie bosses
The ads message applies to you. The advertising id declaration has to be filled out for all apps.
#📱┃mobile would be the place for this BTW
ahh thank you
🍻
@wintry quarry do you know about this? (srry for late response and reply you)
how do you name methods that do a lot at once? do you split them for clarity? i only need it to be done all at once. Maybe DoXDoYDoZ or DoX(bool doY, bool doZ) ?
You want to reduce the reposibility of any method. If it's doing so much you aren't even sure what to name it, it may be a sign the method needs to be split
Make methods that do only one thing
But conceptually, let's say x y and z are "put clothes in washer" "put clothes in dryer" "fold clothes" then a method that does all 3 would be called "do the laundry".
And conceptually it should call those 3 other methods to do the individual tasks
so you would make public method DoTheLaundry and three private methods?
Maybe? Access modifiers aren't really part of the discussion at hand.
That's basically a whole separate topic
Called encapsulation
Basically the idea with both naming and encapsulation is that someone who wants the laundry to be done shouldn't necessarily care about the details of how it gets done
So it's much better to name it "DoLaundry" than "WashDryAndFoldClothes"
i have Ship that can contain ShipPart, ShipPart can be isAdded true or false, and before i add ShipPart to Ship i snap ShipPart to local grid, update it's XY, update it's internals XY, then i use it's internals XY to check if this position is already occupied inside Ship. Then add or not add. So, i name it PrepareForAddingToShip?
What about TryAddPart
And make it check things first, if it can, do it
i already have TryAddPart
I have written it wrong. I snap, update xy in PrepareForAdding and i check XY in TryAddToShip
Well, as they say, the two hardest parts in computer science are cache invalidation and naming things
I'm not sure why you don't check the position BEFORE snapping it and setting its local positions. Like just using a spatial query like checkbox or raycasting
i snap with step of 20m, 20m means 1 in XY
I've always heard it as "There are only two really difficult problems in computer science: Cache invalidation, naming things, and off-by-one errors"
That is so much better
Hello, my game refuses to have my character jump for some reason. Does anyone know how to fix it?
Might want to share some info on the issue(a video?) and relevant code instead of sharing a unity package.
ol
ok
note: I'm literally hammering the spacebar while i was walking
according to the console, the Isgrounded was always false. I don't know how to fix it.
Okay. So start from inspecting where Isgrounded is supposed to be set to true.
Then share the code properly:
!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.
How do I get my ball component and set the color via code?
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Ball"))
{
if (!isPlayer1Goal)
{
Debug.Log("Player 1 Scored...");
// TODO Create a serialized field
GameObject.Find("Game Manager").GetComponent<GameManager>().Player1Scored();
}
else
{
Debug.Log("Player 2 Scored...");
GameObject.Find("Game Manager").GetComponent<GameManager>().Player2Scored();
}
GameObject ball = GameObject.Find("Ball").GetComponent<Ball>();
var ballRenderer = Ball.GetComponent<Renderer>();
cubeRenderer.material.SetColor("Color", Color.red);
}
}
Well, you're doing it with the cube renderer. Just do the same with the ball renderer.
Like this? I'm getting reference errors
var ballRenderer = Ball.GetComponent<Renderer>();
ballRenderer.material.SetColor("Color", Color.red);
How do I reference the ball component in code?
What happened to the code that you shared previously with the Find method?
Also, if the colliding object is the ball, you can get the Ball component from it.
I do now lol
Hmm no compilation errors but it won't change the color
GameObject ball = GameObject.FindWithTag("Ball");
var ballRenderer = ball.GetComponent<Renderer>();
ballRenderer.material.SetColor("Color", Color.red);
Maybe it has to do with material being set instead of something else?
Something like .color
Make sure the material/shader had a property with that name.
That's a sprite renderer. You should not modify the material then.
Instead of getting the base class, get the SpriteRenderer. It has a color property.
okay let me see what I can do
Got it thank you! @teal viper
How do I set it to a random color?
Try googling first. It should find a docs page among the first results.
It points me to Random.ColorHSV which doesn't seem work with it
you aren't calling the function properly
it's a function call
read the error message thoroughly
you are trying to do color = Method; instead of color = Method();
isn't it too painful to look at?
if (shipPartTiles[forX, forY] != null) shipTiles[shipPartTiles[forX, forY].x + 50, shipPartTiles[forX, forY].y + 50] = shipPartTiles[forX, forY];
just a matter of opinion, but yes, hard to read
(IMO)
Tile part = shipPartTiles[forX, forY]; I'd make that, then use it in the if and following
Yes.
better?
shipTileToAdd = shipPartTiles[forX, forY];
shipTileToAddX = shipTileToAdd.x + 50;
shipTileToAddY = shipTileToAdd.y + 50;
if (shipTileToAdd != null) shipTiles[shipTileToAddX, shipTileToAddY] = shipTileToAdd;
ahh null reference
When attempting to access an animation clip using AssetDatabase I get Failed to load "path" File may be corrupted or was serialized with a newer version of Unity. Our project has stayed on the same version and these animations can be handled and used in editor without issue...
Have no clue what could be going wrong
this way will handle the ifnull part, AND is still easy to read if (shipTileToAdd != null) shipTiles[shipTileToAdd.x+50, shipTileToAdd.y+50] = shipTileToAdd;
yeah, i did exactly this)
shipTileToAdd = shipPartTiles[forX, forY];
if (shipTileToAdd != null) shipTiles[shipTileToAdd.x + 50, shipTileToAdd.y + 50] = shipTileToAdd;
not sure if it will help with this issue, but deleting the library folder seems to clear up stuff that looks like some kinda corruption issue for me, fairly often.
ill give that a try
warning- may take a longtime to rebuild
is it possible to somehow serialize this?
public int teleportIndex { get; set; }
field:serializefield
unfortunately getting the same issue
figured out the issue
when testing I was using an animation clip I had made in editor (meaning it was an actual .anim asset) whereas the files I was actually running the script on were .fbx despite them both being 'clips'.
so changing .anim to .fbx in the script solved it 
Im trying to make a game where u can upgrade ur attack
And upgrading it would provide different properties
Like maybe a swing will add a spawn small projectiles to shoot
Or maybe it can reflect enemy bullets
If thats the case, should I use scriptable objects?
that really depends on a lot of different things, but its good to note that you can't serialize SO's, so if and when you modify data like weapon level that will have to be stored elsewhere. With that said SO's are great for static properties / methods... So if you have an upgrade path that you want pre-defined you can have that all pre set in the SO.
serializefield does nothing
So lets say its more roguelike so ir can be random
Does that mean SOs arent odeal
**field:**serializefield
Sorry I completely skipped over that part my bad. Then yes scriptable objects would be great! Just keep in mind that if you want multiple instances of the same item with different levels you may still run into a bit of trouble.
So how should I approach it
Make multiple variations of th weapon with different properties?
Depends… especially with inventory type stuff there isn’t really a great one size fits all answer. But generally in this case, if you are only going to have one of each weapon then SO’s will be great. If there is duplicates but only a set number of them, so long as that number is reasonable then SO’s would still be great. If you are planning on having the same weapon drop multiple times and you want the player to be able to have multiple of the same weapon with different levels you can still use SO’s but you may have to store the weapon level elsewhere like a POCO (plain old C sharp script)
I was planning to do smth like Hades
But instead of a selection to choose from we only have one
And as u progress in stages, you can choose upgrades that adds new properties to the weapon
Aside from that are boosts like movement speed and health
I think solid stats arent too dofficult to adjust
But the weapon additions are what im struggling with
From the sounds of it Scriptable Objects for each of the weapons will be a solid system. As for upgrades that one can be tricky depending on how scalable and or universal you want things to be. I don’t know if I can give you any good answer for adding them to attacks as combat is a whole other ordeal that I’m just beginning to learn as well. But I would recommend starting by handling attacks from each SO where the attack code includes all of the effects / upgrades to the attacks locked behind if statements… that may not be the best system in the world but starting on something simple like that will get you moving in the right direction.
Unfortunately running into problems is really the only way to learn if something works or not. You just kinda have to go for it and throw stuff at the wall as sucky as it is
Can someone explain why this code doesn't print SUCCESS ?
{
int seed = UnityEngine.Random.Range(1, int.MaxValue);
System.Random oneInSix = new System.Random(seed);
System.Random fiftyOneinSixtyTwo = new System.Random(seed);
int roll1_6 = oneInSix.Next(0, 6);
if (roll1_6 == 5)
{
int roll51_62_fourTimes = fiftyOneinSixtyTwo.Next(1, 63);
if (roll51_62_fourTimes < 52)
{
roll51_62_fourTimes = fiftyOneinSixtyTwo.Next(1, 63);
if (roll51_62_fourTimes < 52)
{
roll51_62_fourTimes = fiftyOneinSixtyTwo.Next(1, 63);
if (roll51_62_fourTimes < 52)
{
roll51_62_fourTimes = fiftyOneinSixtyTwo.Next(1, 63);
if (roll51_62_fourTimes < 52)
{
Debug.Log("SUCCESS!");
}
}
}
}
}
}```
Is my brain completely failing to grasp something or is this an issue with pseudo-random generation? I am trying to complete a 1/6 trial followed by 4 consecutive 50/62 trials. If my math is correct, which it may not be, I would expect about a 6% success rate, yet in 10,000 trials, Success is never printed. I feel i am definitely missing something regarding the way Random works...
move your seeds outside of the for loop
My goal is to find a seed which will grant a success on its first attempt, so i need to check a new seed every-time... shouldnt this still have about the same chance of success? or does it somehow change the probability?
if course it changes. what you are now trying to do is hit success on the very first go of a seed, the chances of this happening are virtually zero
to try what you want you need to change
int seed = UnityEngine.Random.Range(1, int.MaxValue);
to
int seed = i;
and it's all well and good just printing out SUCCESS!. You still have no idea how it got there so the whole exercise is pointless
It’s a simplification of a larger process
I don’t conceptually grasp how this is different but I’ll give it a go!
Yeah still no success
the difference is it gives you control over what happens after. At the moment you have no clue as to what is being fed into the algorithm. So Garbage in, Garbage out
And you still have no idea why it is not working
No
Then ask yourself, how far down my logic do I get?
It shouldn’t matter if you stay with the same seed or change the seed every trial… if the Next() number is always random, then it should be just as likely to hit the success on the first trial as the next… no?
yes, and the chances of that happening 5 times in succession are virtually zero
but im not trying to find a suitable seed 5 times in succession, just one suitable seed that works on 5 consecutive trials (6%)
but that is not what your code is doing
well what would the code look like if thats what it was doing lol
for (int i = 0; i < int.MaxValue; i++)
{
int seed = i;
thats gonna run 2 billion times...
2 billion iterations...
probably multithread it
yep
you're trying to find a seed which does something very very very specific, this is gonna take time no matter what you do
well, you return i if you hit Success
why do i need to run 2 billion times if my expected success is 6%?
or looking at the algorithm on how the .Next output the int and try to find out the bit patterns
you need to find which one of the 2 billion is the right one beacause you do not know
How do i make a firework and tool system like firework mainia
what is firework mainia
A game on steam
its not that specific, its above 50% in 4 of the 5 trials
i dont think this will be feasible, random algorithms are designed against this kind of attack. would be analyzing a ton of numbers
"Here, lemme give you a 10-page answer to that question real quick"
is my calculation of 6% wrong?
How about something more specific, what exactly are you having a problem with?
🤷♂️ i dont know where u got 6% from in the first place tbh, what part is 6%
it is not cryptosecurity random number generator so it should be possible? though it is still quite hard to reverse engineering
true but still would require some decent beginner knowledge to even know where to begin
closer to 7%
is 51/62 indeed, so a bit higher
the range is [1,52) so 51 possible number, the min should be inclusive
Also this is based on one seed. You need to know the seed value first
ok so i have a 7% chance based on one random seed?
if i repeat for a ton of different seed shouldnt i get a success after 100000 seeds?
so stop changing the seed every loop, do what I first said and move that out of the loop
i did....
it didnt work
right which means that your 7% is wrong
yes but why
no idea, I'm not a mathematician
are u sure u saved your script or something after moving the code?
i tested this on a online compiler and i get success printed
whats your code?
quite literally the same thing you posted, with moving the seed part outside the loop
only changed debug.log and the unity random because im using an online compiler
yeah but that doesnt solve my problem
My goal is to find a seed which will grant a success on its first attempt, so i need to check a new seed every-time...
which your code does not do but my amended for loop does
I tried what you suggested idk what you want me to say
sorry im getting sassy lol
yall just trying to help
but it doesnt make sense
what you tried this? #💻┃code-beginner message
Not that one. 2 billion is gonna freeze up my machine
coz thats the only way to find the seed you want
but why.... the success rate should be so high
need a math person to explain it to me
i need to go back to stats class
logically.
If the success rate is 7%
and you want to hit it on the first go then...
the correct seed should be 7% of all possible seeds so...
you need to find that 7% within the int.MaxValue range
so how much of int.MaxValue is 7%?
right so logically if you loop for 140m you should find 1 which works
assuming non random spread
ok im running it now 🤞
Sorry but that makes no sense at all. If there's a 7% chance then running it 100 times gets you through on average 7 times, regardless of how many possible seeds there are. By the same logic if there's 100% chance to succeed on first try you'd need to loop through all int values to find one.
I think this is the problem:
System.Random oneInSix = new System.Random(seed);
System.Random fiftyOneinSixtyTwo = new System.Random(seed);
You're using the same seed twice. If oneInSix rolls high then fiftyOneinSixtyTwo also rolls high on the first go
I'm not sure why he has 2 different randoms either
his probability calculation is surely based on using the same random seed for all throws
From experimenting actually, this seems like the perfect number choice to be impossible with what Nitku said. If the first number rolls 5, the second number is always 52 or higher..
just curious where have u come up with this problem that needs solving? Is this like some question you were given as a challenge online
this is it
this is the info i was missing
i have a game which uses seeded runs. I need a seed for the tutorial that meets certain criteria
Very unlucky that you needed the exact numbers that weren't possible with your code
lol yeah but i shouldve figured it out sooner
when i was first running it i was like why is the first number (after 1/6 trial) always high? but then i kinda got rabbitholed
big oof
I assume random.next uses decimals then and multiplies to get within the range specified, rolling a 5 from 0-6 would be 0.833 and above. 0.833*62 is just 52 if rounded up
damn thats brutal
woulda saved myself so much time if the numbers were just slightly different
it has to do with item droprates
but i wouldnt have learned 🤓
Guess it's good to know for my game too which relies on rng heavily
how do I handle coroutines in non-monobehaviour classes?
i.e.
I have a GptApiClient class that I use to post a message and receive a response from the OpenAI API
what I did before was make GptApiClient : MonoBeheaviour and then access it through a singleton. that allowed me to start a coroutine for the PostMessage function.
Trying to refactor my code now so that GptApiClient is just a public static class that doesn't extend from MonoBehaviour, but now I'm confused as to how I would handle the coroutine?
you can run coroutines on another monobehaviour, but if that other object gets destroyed then itll also stop the coroutine I believe.
oml so many successful seeds 😭
If you really don't want to use a MonoBehaviour, you could make an asynchronous Task
Though this does need to call back to the main thread
But you're better off having a Monobehaviour do it
But you can totally iterate the IEnumerator from a Coroutine yourself in a way, it just takes time to implement and I doubt it's any better
Are u just reusing the same one random instance now? I assume that's the easier fix for this. I was reading before 1 in 140m seeds and was thinking this makes no sense but had no other explanation why it didnt work lol
Needing a Coroutine for a PostMessage is weird though. Can't you do this asynchronously rather than polling for a result?
no I just skip the first Random.Next() for the second random instance
The instances must stay separate cause they control different aspects of the game
so random instance 1 checks the first value and random instance 2 checks 2-5 values
I see, I guess that can be useful to get the same generation each time with a certain starting seed
we use this kind of thing a lot in Casino games because it allows us to exactly tailor the win/lose chance of the game
Hi guys, i am building a linux build using IL2CPP on my Mac (intel chip) for a dedicated server, and it's taking forever on the Linking GameAssembly.so (x64). Is it normal ?
is this a code related question?
not really but i could not find where else to post it, can you tell me please ?
oh okay. That could be 150% quality of life
Just replace it with { get; private set; } of course.
Field initializers run before the class constructors so technically this does not exist yet
Not sure why you would need to do this since it looks like a bad dependency loop, but maybe you want to use a generic type instead?
i'm not sure, i'm just refactoring my code to make it look more clear and with less lines
I see, why do you need this in this case?
ActorLogic will use this Actor later. ActorLogic had SetActor method and i wanted to remove it
yesterday it all was in Actor class, today i wanted to split my giant wall of text into several classes
ActorLogic will only exist inside Actor
Right, usually something depends on another thing but it would not go into a loop like this
Because this is a way to get stuck with dependencies
So if both things depend on eachother maybe it should just be one class
Or maybe Actor should inherit from ActorLogic
If you want to separate logic from data, it's usually the other way around: MonoBehaviour contains the logic, while a plain class is used for data.
Actor has logic related to basic things like moving, turning, shooting while ActorLogic has logic related to it's AI
i'm bad at organizing it)
Might be better to name it appropriately then. Maybe even make it a separate MonoBehaviour.
Then just make it an abstract class you can inherit from
And the logic class inherits itself from MonoBehaviour
do people usually spilt their big classes with inheritance?
Well your class is a base class that contains movement and all that
You can also just keep it a separate class and emit events from it depending on how you move
Whatever you do, you should not have to make a looping dependency like this
if i call some method inherited from parent class, is it faster than calling some method from other class?
Don't worry about performance
It's not something you should think of, especially not here
There are some specific rules but those are not related
what exactly is looping dependency? like if two classes depend on each other's methods?
Yes
You should not need that because then it should just be a single class
Usually A depends on B, and B will emit events that A should then subscribe to
the coroutine includes an Action<GptResponse> onResponseReceived as a parameter,
so it's basically
yield return request.SendWebRequest()
var response = JsonUtility.FromJson<GptResponse>(request.downloadHandler.text);
onResponseReceived.Invoke(response);```
does that make sense?
yeah
I think that's more or less how you're supposed to do it according to
https://docs.unity3d.com/Manual/UnityWebRequest-SendingForm.html
Eh I'm usually against these things, especially now that Unity has better support for Tasks so you could just use HttpClient
that is deprecated iirc
the old web request system
I get this error but how can I search and find my object by this ID?
Can't Generate Mesh! No Font Asset has been assigned to Object ID: 88474
Sometimes logs have added context to them. If you click on such a log, the context will be highlighted in your scene/project. Dunno if this particular log has it though.
i want to make a game where a storm is created every 1/10000th frame. i have 2 scripts at the moment. 1 where i want to start the storm itself based on what type it is. but in my 2nd script i have the type of the storm that i want to give to the first script.
my question is, is it easier to just combine this into 1 script or is there a way for me to easily link these 2 scripts?
I think you should revaluate how much you want to get done in a single frame
quite new to unity and dont know how everything completely works. seems to be working fine atm. just want a way to link 2 scripts between one another or if i should do it in one script.
up to you really how you do it, both are valid
Oh, you want to spawn one for every 10000 or so frames that have passed, is that what you're doing.
do you really care about frames, though
or 10000 objects per frame, maybe I should make myself a coffee
or do you care about time
You almost never measure durations in frames, since the player's framerate will be varying (and different players will experience different average framerates)
yes it is
i have a 1 in 10.000 randomizer that gets pulled every update()
;-;
it's very easy to have two scripts communicate with each other once you understand the basics of C# and Unity.
maybe doesnt work that i usually work on arduino and other embedded systems that use a "loop()" function
i understand c#, just not unity that well if im honest
communicating between scripts isn't that much different in unity than standard c#
unity update is running inside a loop
while(1){
update() and other monobehaviour messages
}
the only differences is monobehaviors + inspector
yea this throws me off a little ngl
basically any public/private serialized references of scripts/components can be linked in inspector
since monobehavior can't be created with new()
so if i want to refer to another script, i can drag it into my other script using the inspector or what?
unity does that when its on an object
ahhh
yea pretty much, you make the reference/field for it first then link it thru inspector 🙂
ahh gotcha, thanks alot. ill go try that now
Just be sure you understand the difference between a script (the script .cs file itself) and an instance of a script attached to a GameObject. It's the latter you will be dragging around into inspectors.
yea no i got that. to me that translates over p well from c# itself
you just need to reframe this in terms of a probability per second
If you want an event to happen once every 1000 seconds, I'm pretty sure that's just:
oh wait, it's not just that
if (Random.value < 0.001f * Time.deltaTime))
This is wrong. If Time.deltaTime was 1000, you'd have a 100% chance to trigger the event
(well, unless Random.value returned 1, which it can do: it's inclusive)
it's been a few years since i took that randomized algorithms class. i am bad at this
oh god i'm getting nerd sniped here
the objective is to, for a time interval, calculate how many events have occurred
it's easy to calculate the expectation (the average value), but I'm not so sure about randomly drawing
this is probably irrelevant, though, since your game will be running at way more than... 0.001 FPS (:
it's a decent enough approximation
isnt it better to use coroutine for this?
That would be a reasonable choice! you'd just randomly pick a delay.
That sounds more consistent. The player wouldn't expect two rare events to occur back-to-back
what is this component?
check the value and options properties
how would i make a prefab have a sprite then switch to an animation after colliding with an object in unity 2d
animator
please elaborate
Animator controls what happens to sprite renderer
switching to animation would be as simple as switching state
public class airplanemovement : MonoBehaviour
{
public float speed;
public float turnspeed;
public float axisx;
public float axisy;
void Start()
{
}
void Update()
{
axisx = Input.GetAxis("Horizontal");
axisy = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward*speed*Time.deltaTime);
transform.Rotate(0,axisy * Time.deltaTime * turnspeed,0);
transform.Rotate(axisx * Time.deltaTime * turnspeed, 0, 0);
}
}
this script should change the direction of the plane:
with the horizontal axis it should change between left and right, with the vertical it should change the height, but it inverts them: with the vertical left and right and with the horizontal the height
i should remove void start btw
you've been here long enough to know how to share code no 😏
hehe
im doing that rn
at paste of code
navarone is the real OG
https://paste.ofcode.org/6rc9gjSQpHg5pfmXAzPE4A
i fixed it by inverting x and y, but shouldn't be x before y?
yo @rich adder add me on discord friend if u can
no
X axis is always up and down
rotation wise
oh i think i get it
z forward, x right, y up
So, just started working with unity like a week ago. I already got experience in GameMaker, but i wanted to do more "professional" games.
Im doing a mobile game that everytime you click on the screen, you spawn a new unity thats called "ally". It'll already have enemys in the scene, and both allies and enemys will have an AI, so they will run to eachother and attack when they have range. The enemy will be stronger than the ally, so you will need to create a strategy to win (for example, click faster to spawn a lot of allies, or flank the enemys clicking on different locations of the screen).
Ok, the "gamedesign" is basically that. The playerr only job going to be click on the screen, and watch the war happens.
But im having an issue. Since in new to this, im having MAJOR issues at programming the attack damage, and the hp.
heres the code for both EnemyController and AllyController: https://paste.ofcode.org/wjd7SkmhDtTfuUYMfj2QZu
So i guess the problem is there im calling the damage a lot of times and its not proper working, the ally is not killing the enemy while the enemy can kill the ally without problem. PLEASE can someone help me?
Oh, and another thing, ignore the // comments, im Brazilian and I wrote the // comments on portuguese, my language. Just ignore.
And also ignore the animations code, i used a transition.
Please help me to get my game going correct ❤️
Sorry for the huge text wall guys
lol we didn't need the whole backstory 😆
hahahahaha its better with the backstory so u guys can feel my pain
nah im just jk but yeah its hard to read what the problem actually is
so the ally can't kill enemy right ?
i havent send the code for GameController, but is basically just instantiate when u click
all the attacks and debugs are working ?
yeah thats right
i cant send u a video of the game if u want
Yes, don't leave empty methods in your classes, they still get ran
Hey is there a channel for playstation here ? Cuz I get lots of wired bus on a playstation port but in editor everything seems fine
esp Update
if no channel fits #💻┃unity-talk
no, PS requires a dev agreement/ license with Sony and is NDA'd
The project is a work project
ok?
Use the closed Playstation forums
you can't legally discuss PS development outside of the closed forums
Heres the vídeo
the video about this issue
oh jeez someone needs to learn about OBS 😅
lets make a thread rq so we don't flood chat
hahahahahaha im no streamer bruh
ok ok bro
thanks a lot for your willing to help
Hi, is there a way to retrieve the current focused go from the standalone input module component?
currentSelectedGameobject from the EventSystem doesn't appear to be working on UI elements
Ah, UI specifically I think I recall a method for that, but usually the event system has that info too.
maybe I could find it if unity decides to be nice and open one of my projects
Ah, this maybe what I'm thinking of. Was using it for a hybrid keyboard w/ onscreen
I want to spawn some orbs after an enemy dies in a parabola arc until they hit the floor. Is it more performant to use code driven arcs rather than rigidbodies w/ gravity?
if you're not using colliders for your first method than it would probably be more performative otherwise probably not too different.
actually non-kinematic rigidbodies would still have a lot more overhead so if you are spawning hundred of orbs then it's best to avoid it
I am not sure how I'd get the hovered object from that tbh
Are you using a pointer
I see I could use colliders but also have them do overlap sphere even?
Heres what im trying to replicate
https://youtu.be/B7IHMtRMR50?feature=shared&t=63
How to loot the Mimic/Fake treasure chests in Nioh 2.
-When you come across a chest in Nioh 2 that has three gold bands on the side instead of two this means that it is a mimic chest.
-To deal with it without fighting simply use the whistle gesture and then copy whatever gesture the clone uses.
More Nioh 2 Guides!
Purple Kodamas Explained: http...
yes
There's IPointerHandler for when you want to specifically call an event when you're over that specific UI element
yeah, wish I could use that
oh, there's also probably a buffer you can read from for current hovered gameobject
I'd just use a regular unity event and then pass that object in the inspector
but our uni forces us to use visual scripting and I don't feel like living :/
ik that this isn't the visual scripting channel, that's why I asked a specific question about the thing that held data that I needed and it's fine if it's not possible to retrieve it, will find another way ig
Hmm, there is IsPointerOverGameObject, but you may need to raycast yourself onto the UI and grab the element to compare or however you want to use it
why can't you use IPointerEnter, IPointerExit?
and cache the last hovered UI object
oh okay didin't read the visual scripting part
I am using the event tirgger on pointer enter
yea that's pretty much the same
Right, you can actually ignore colliders on the orbs if you wanted to and just check collision with overlap if you want to. More control too like disabling checking when the object is set, ect.
yeah, I was looking for a way to do that, how
sounds good thanks!
mao recommended rc which seems reasonable but I was hoping that it's possible to retrieve it from the standalone input cuz it has a focused object var but it is prob private
implement the interfaces
make a "SelectionManager" singleton or something
and cache it there
whenever OnPointerEnter triggers
yeah ive no clue about visual scripting beyond the vfx / shader graph haha
for sure you can do this
can't do it from EvenSystem.current iirc
you either need, as Mao said, make a custom raycast (graphic raycast, not phyiscs raycast)
i think you can also do EventSystem.current.RaycastAll()
EventSystem.current.RaycastAll(new PointerEventData(EventSystem.current) { pointerId = -1 }, results);
if (results.Length > 0)
{
GameObject hoveredObject = results[0].gameObject;
Debug.Log("Hovered object: " + hoveredObject.name);
}
I would expect currentgameobject from the event system to work if you're hovering over buttons and stuff, or any UI element with selection interface implementation
sth like that
yea im surprised it doesnt, if we have "IsPointerOverGameObject()", why can't we cache that object we are "over"
well I attached the EventTrigger component to my texts but they don't get selected in the event system
and I do have my event system properly set up in the scene
i see
You need a Selectable inheriting component
such as Button, Slider, Dropdown, Input fields, toggle etc
So in this case you'd raycast and compare against if it's selectable
oh wait, you're looking for a transform here. You'd want a rect transform.
better to grab by the type than transform values anyway
Get Current Selected GameObject -> Get ISelectable, or button if you only need that specific type.
well the issue is that even tho the element has a button component attached, es doesn't recognize it as a selected object :/
Hi. What is the name of the library that fills the blank for using ___ for the TextMeshPro (TMP) library?
[SerializeField] TMP_DropDown dropDownObject;
I'm trying to do this but Unity says that it can't find the type TMP_DropDown so I suspect my library name is wrong. I've tried a few, like TMP, TMPro, TMPPro, etc. but none work.
Also struggling to find this information online (probably looking in the wrong places).
when you type TMP_ you get all the suggestions like namespace too
are you not?
I tried that because I sw it at the link @polar acorn sent, but it still doesn't work?
Do you have it installed
Oh 🤦

DropDown vs Dropdown. Sorry guys
.value
Never mind, still getting the same error.
what error
About to send 🙂
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class DropDown
{
public DropDown()
{
}
[SerializeField] TMP_Dropown dropDownObject;
My code ^^. The error:
CS0246: The type or namespace name 'TMP_Dropown' could not be found (are you missing a using directive or an assembly reference?)
Line 13 is the line where I serialize and define dropDownObject.
What's a Dropown
what "doesn't work" mean
Neither of those are .value
If you need the value from a slider, .value is how you get the value of a slider
You probably wrote your own class called Dropdown, attached it to a GameObject, and then later removed the MonoBehaviour part from it?
This is TMP_Dropdown, not related to your error
I renamed the script and changed the class name and constructor name to match the renamed script
And it did that
But I've done that a bunch of times before, and it always work.
There should NOT be any constructors on a MonoBehaviour
show what you're trying to do
If it has a constructor then that means it's not a monobehaviour, your error shows you've tried to add it as a component to something anyway
It's not a MonoBehaviour
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Dropdown
{
public Dropdown()
{
}
[SerializeField] TMP_Dropdown dropDownObject;
TMP_Text dropDownValue;
void OnValueChanged()
{
dropDownValue = dropDownObject.captionText;
}
}
So, this is not a component. You cannot add this to any GameObjects
Ahh that'll be the issue then. Can I still use it in a TMP_Dropdown gameobject's OnValueChanged() function, for example? Where I drag the script in and select a method to be ran.
No
How would you reference an instance of it?
Also probably not a good idea to name a class the same thing as a Unity component
y x = new y();, right? Removing MonoBehaviour allows that I thought
How would you expect to use that in the inspector though
I just want the script's OnValueChanged() method to be run whenever the TMP_Dropdown object has its value changed. Then I would need to access the text of the selection made, which is within the captionText attribute. I would need the class to be instantiated for that, right?
desnt dropdown already have its own ValueChanged you can sub to another MB?
whats the point of this class being a poco
Poco? Sorry, new to Unity 🙂
plain old c# object
Haha
"Plain ol' C# Object" as in, not a monobehaviour or component or anything
And what do you mean 'sub'?
https://docs.unity3d.com/Packages/com.unity.textmeshpro@2.0/api/TMPro.TMP_Dropdown.html
this already has event
subscribe to an event
ie run this method when value changes on dropdown
there are multiple events too
So I've created a method in a script and I've added that as a component to the TMP_Dropdown GameObject. Is that what you mean by subscribing to an event?
I only need that one for now, so it hopefully won't be that difficult.
Subscribing to an event would be adding the function you want to call to the OnValueChanged callback on the TMP Dropdown itself
Yes I believe I did that. Let me send you a screenshot.

