#💻┃code-beginner
1 messages · Page 770 of 1
Queue would work fine if the idea is you're executing as you pop dequeue them. List works fine too though as you can just get the count and pop from the end of it
Really the queue is just a more restrictive list when you think about it (c# list allows 0 index insertions). Something like a stack however has some more usage imo
why does adding an editable list break the editor?
Reset the editor
this happens every single time I look at an object with an editable list, without fail
also would that just mean close it and relaunch the project or
Yeah, restart unity. Also this is a coding channel, so if it persists and you think it's code related then post some code, otherwise take it to #💻┃unity-talk with any other information you can provide.
Seems more just like Unity bugging out though, but if you do have plugins or something going it may be conflicting
Are you sure that the constraints are 100% and not causing some off call?
I don't
what version are you on?
whatever the newest version was before the security flaw thing
How to check at a negative angle until a different angle?
if you could somehow figure that out lmao?
I cannot
what does that even mean
checking if an angle is between two angles
idk how else to explain
let's start by explaining what you are actually trying to accomplish
https://xyproblem.info
so checking if 2 angles is a certain degree?
for what
alright i'm out
trying to find out if door is open im assuming ?
cause I have said I dont know how to explain it
I can do that
if you cannot explain what you are even trying to achieve then how do you expect anyone to know what you actually need to do
But I want it to be able to close, not instantly but after it goes above (below in this case) a certain angle
well
open
not close
close after opening, just not instantly
allowing you to
oh like lerping?
I've done that I just want to check if the doors rotation is gone past a certain angle
after opening.
Oh okay, so seeing if max threshold has been exceeded?
Max threshold is about to be exceeded
idk anymore
its hard to explain
and its confusing
finish a thought before pressing enter rather than spamming one thought across 4 small messages
#📖┃code-of-conduct
nvm i figured it out somewhat
can you post the code because im curious as to what you meant
I not figure out
i hate rotations so much
I'll see if I can explain this better
rotations are not bad once you understand all of the ways to make it work
Can you post a version of the not working code as well
Why don't you just rotate the object over x time using lerp, and then when x time is up, rotate it back the same way?
I saw someone mention coroutines, did you try using them?
So i want to check if the doors rotation is IN between or equal two angles, -15 and 0. And if it is in between or equal allow the input.
something like that
I will eventually use them just not for this
if (Mathf.Abs(currentZAngle - targetZAngle) < 5f)
Mathf.Abs takes a single numerical argument (which can be an int, float, long, sbyte, or short).
I know what converting to positive value means. But I will test this out rq
alright
Mathf.Abs in Unity is a static method belonging to the UnityEngine.Mathf class. It is used to return the absolute value of a given number.
YES OMG
feel good
I really need to learn more
arguments
also this is my code btw
about to fix it
Having that in fixed update will lead to some issues but for now is a great way to proof of concept
its just a placeholder for me rn
I'll be doing something completely different later on
perfect
I do plan to make it an animation
instead of just rotating
literally
but, eh.
This solves one of my problems that totally hasn't taken me idk, 12 hours to figure out?
and I didnt
you could move all of that out of fixed update into a void like
//After key pressed do raycast check this away the raycast is only being cast once and not over all the time causing issues
}
Ya Update or Fixedupdate raycasting is heavy on pc's to make it simple
If you weren't using methods you wouldn't be running any code.
something like this?
Or do I do return hit
Update and whatnot are methods just like any others
personal methods
methods I create
using the code
nvm you cant return hit
wait. I am using raycast like every frame that an object is held in my game. Is this bad? should I find an alternative?
You probably want to do something with the return value of that raycast.
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Physics.Raycast.html
you can just not like that hold on one sec ill write it out
right now it's just being thrown away. (Well, right now it's a compile error but I'm assuming you'll be passing in the values later)
Is there a difference between registering and subscribing to an event?
Or are they just synonyms
Yep, it's the same concept
{
if(interact.action.IsPressed())
CheckDoorStatus();
}
void CheckDoorStatus()
{
currentRotation = transform.eulerAngles;
if(Physics.Raycast(mainCamera.position, mainCamera.TransformDirection(Vector3.forward)* raycastDistance, out hit, layermask))
{
if(Mathf.Abs(transform.eulerAngles.y - closedTargetRotation.y) < 5f)
{
currentRotation.y = Mathf.LerpAngle(cirrentRotation.y, openTargetRotation.y, speed * Time.deltaTime);
transform.eulerAngles = currentRotation;
openInput = true; // not even sure you need this
}
}
}
ahh
this will limit ray call and and help clean things up i typed this in a web app so might need some tweaks but concept is there
I was just tryna get the premise down for my code
like not, whats the word for making the game run better
optiomized
optimized
this will make it where the raycast isnt going crazy
oh i know you would have most likely done this i just like to make things slightly optimized when it comes to raycast as to many ray calls will cause major performace issues
yeah I get what you mean
I just wanna get the premise working before optimization
since I'm new to Unity
then you go down the rabbit hole
wdym
this is my current WIP on my state controls
(Crouch.inProgress ? MovementState.crouching : !move.inProgress ? MovementState.idle :
Sprint.inProgress ? MovementState.sprinting : MovementState.walking);```
{
switch (state)
{
case MovementState.idle:
Debug.Log("Player is idle.");
// Add idle animation or behavior
rb.linearVelocity = Vector3.zero; //current not working right but i think its from ground check issues
movementState = MovementState.idle;
break;
case MovementState.walking:
Debug.Log("Player is walking.");
movementState = MovementState.walking;
break;
case MovementState.sprinting:
Debug.Log("Player is sprinting.");
movementState = MovementState.sprinting;
break;
case MovementState.crouching:
Debug.Log("Player is crouching.");
movementState = MovementState.crouching;
break;
case MovementState.air:
Debug.Log("Player is in air.");
movementState = MovementState.air;
break;
default:
Debug.Log("Unknown player state.");
break;
}
}
ah huh
thats first code controls my entire player motion in one line depending on keys used
It's a switch statement which takes an enumerator and depending on which it is, outputs the code in the case: section
So if for example you were to have an enum as A, B, C, D, you can have case A: DoAMethod(); break; case B: DoBMethod() etc and it's within what's known as a switch statement that's the switch(enum type name here)
not an enumerator btw
enum stands for enumeration
It's an enumerable value
nope, different thing
it's an enumerated number
an enumerable is what other languages might call an iterable - lists, arrays, dictionaries, etc
(same for enumerator/iterator)
an enumeration numbers (lists) out the possible values
So youre saying, an enumerator isn't an enumerable although they are lists that are 'arguably' finite, to enumerate through something is to go through each step by step usually in order.
Regardless, I shall look into this further
enums aren't infinite btw
an enum is neither an enumerator nor an enumerable
an enum is an enumeration
also whats this thats highlighted meant to mean
If the maths.abs is greater than 5
there are beginner c# courses pinned in this channel, perhaps start there if you are unfamiliar with common comparison operators
I know what that is
thats not what Im asking
and idk why, but this helps
Im weird
perhaps be more specific
"i know what that is"
someone explains what it is
"that helps"
ah im not going to bother arguing
MathF.abs is taking the absolute value of the sum in its method, and checking if it's greater than your 5, an absolute value is basically even if the Sums a negative, it's positive version is the absolute
that isn't a sum btw
the absolute value of a difference gets the.. well, absolute difference. a difference without a sign
Absolute of -5 is 5 as an example
absolute value doesn't care about sums. you referred to "the sum" in your example
absolute value gives the absolute value
both of you know what mathf.abs is
The sum is a synonym for total, so your sum is the end result
lets just not argue about it :3
yeah no, that's not what words mean
exactly
You've never heard the term sum total?
i have, and it's not relevant to absolute
sum is the result of additions
there are no additions here
if I Mathf.Abs(-4) is there a sum?
there is not
The Sum total of abs(-4) is 4
Often denoted in books as |-4|
maybe look up what sum means
Oxford languages
I think saying |-4| gives a sum total would be the same as saying sin(4) gives a sum total which... doesn't make sense to me. not a mathematician but that sounds odd
I think you need two numbers for it to count as a sum
not just any 2-input operation
what have i come back to
|-4| does have a formulae to it, it's not just remove the negate sign
the result of subtraction is a difference, multiplication is product, division is quotient for example
it's only addition where the result is a sum
I'm ngl I completely forgot, I thought subtraction counted 😔
i believe everyone here is aware. it's simply not a sum, and that is a fact
Are you going to carry on being this irritating and unhelpful?
Or should we summary this
come on man...
are you going to keep insisting on wrong terminology lmao
it's an active detriment to beginners to be taught the wrong terminology
it creates a communication barrier, making learning/researching harder
ive tried to be helpful, ive explained the correct terminology and ive explained what the terms you used actually refer to
up to you if you want to accept that and learn from mistakes
mistakes are a crucial part of learning, ive made a ton myself. it's fine
you don't need to accept it to me or anything, but at least accept it to yourself so you can learn
The issue in this, and my issue mainly is not how you have corrected me if you correct me, it's how you do so that's the issue, as you have done with others before
your issue isn't how i correct you, but how i correct you?
It wasn't 'constructive' is what I mean, it was confrontational
tbh, i think i started pretty light. you kept deflecting
i explained in detail what each term meant. what do you want from me
Sum, summary, total synonyms, you told me they were not and sum and total were not
I can't imagine this convo ending well :c
I think we should just leave it here
nothing is going to be gained going forward
...well, i tried...
Never ends well, I'm used to it, I just watch the chaos from afar now
why are people so resistant to learning
Isn't it obvious
i would hope so
I assume they learned but yk. It became an argument instead of a discussion and at that point neither side is ever backing down 😔
also sum and summary aren't synonyms 🤨 though that wasn't brought up so whatever
anyone now what he is using?
A keyboard most likely
looks like a public variable, but I'm not sure the name of it . . .
this question is a bit too vague it seems...
-# looks like they're using dark mode to me
and when i open a c script were is the option playercam
He created a script and named it PlayerCam
should be "MonoBehaviour script" iirc?
thank youu that actually helps and is the thiing hes usiing the visual studiio
yeah
ok thank you
(sidenote - visual studio (vs) and visual studio code (vscode/vsc) are separate things. blame microsoft for confusing naming. both are valid options though)
how do i move the arrow to my mouse?
so if i put my mouse in the position where the red square is... the arrow should rotate around the circle to face the mouse new position
the arrow is a separate object
What have you tried so far?
making it one object worked fine but i want it to be two so i can animate the arrow differently from the circle
if so, I imagine parenting a logic object to the arrow and underneath the circle and putting all the direction logic on the empty object would work. At least, i'm assuming what's broken is that the pivot is now off, so you can just... move the pivot!
thanks this will probably do the trick
np ^^
Show your current implementation else there isn't much to add since this is a coding channel. With no other information, I could only suggest probably using https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Transform.RotateAround.html
Anybody got any guitar hero style scripts that work with a ui slider and ui buttons
sounds like something you could put into google
not sure how sliders would fit in there though
Thinking about combining the functions for pressing the buttons on the screen to make the bar slide
Example being rect transform
hi guys im making a weapon bench in my game when u enter it switches the input map but when i try using it nothing happens no errors no debugs that its null even tho i enable them all
`var values = playerGeneralValues.Instance;
if (values == null)
{
Debug.LogError("playerGeneralValues instance is null!");
yield break;
}
values.playerInput_i.Enable();
// Get and enable the weapon bench map
weaponBenchMaps = values.playerInput_i.weaponBenchMap;
if (weaponBenchMaps == null)
{
Debug.LogError("Weapon bench map is null!");
yield break;
}
weaponBenchMaps.Enable();
// Find actions
leaveAction = weaponBenchMaps.FindAction("leaving");
clickAction = weaponBenchMaps.FindAction("click");
mousePositionIA = weaponBenchMaps.FindAction("mouse");
// Verify actions were found
if (leaveAction == null) Debug.LogError("Leave action not found!");
if (clickAction == null) Debug.LogError("Click action not found!");
if (mousePositionIA == null) Debug.LogError("Mouse action not found!");
// Enable actions
leaveAction?.Enable();
clickAction?.Enable();
mousePositionIA?.Enable();`
i am not using a player input component
perhaps ask #🖱️┃input-system, and show how you're receiving input
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
the error message itself isn't code, but putting it in a code block (or a pastebin if it's long) doesn't hurt
makes some parts easier to read, but not a requirement
ok idk how paste.mod.gg works i'ma just do the inline code one
(btw that embed is available in #🌱┃start-here, so you don't have to summon the bot every time)
I don't see it there-
ah it's not that embed exactly, but the sites are here
#🌱┃start-here message
as for the inline code thing, you can just type those
oh yeah the sites yeah
I should be able to remember the inline thing hopefully
(technically it's not inline code (which would be this), it's a codeblock... not sure why the embed says that 😔)
hey, how do i create an enemy AI that shoots towards you and follow you
U can use state machine combined with scriptable object to store the enemy's states. If u want smarter movement (to avoid walls, doors, etc.), u can use navmesh
i think he is using 2d envoirement
Yeah, just a heads up
it seems like i have some bug that wont open the game mode, while the code seems normal
Is there any other error in the console?
I got this message and don't know where the error is coming from
the error tells you
seems like your vs is not configured
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
The error suggests missing bracket but everything does look ok
there's a missing bracket, exactly like the error says
i've been seeing it from time to time but i'd like to know just to be sure; what's the difference between struct and ScriptableObject, and when would i want to use one over the other?
The bracket that covers the whole class?
yes
they are significantly different things
oh
can't really compare them
well can you give me a rundown of scriptableobjects then?
structs are bundles of data (for processing, etc)
SOs are configuration data (static)
right
in what situations would i use SOs then? i'm looking through the ror2 code right now and the items are all SOs but i'm not quite sure what that means in terms of how they function
that's pretty much all structs are, they're just a language feature, they can be applied in a variety of circumstances
SOs are a unity thing, basically data as assets
ah right
so SOs are easier to use within the editor and are more versatile, but structs are simpler and smaller?
or am i getting this very wrong
each SO instance would be represent the data of an item - sprites, ids, how they're used, etc. could apply to a lot of things, idk the specific usage you're talking about
U can use struct in SO
close, but
more versatile
i wouldn't say they're more versatile than structs
and vice versa, you can do composition with most things. that's how composition works
SO is just normal class
i might have to look into this a bit more then
SOs definitely aren't just normal classes, unity specifically knows about SOs and can instantiate them as assets
(to be clear, not saying structs are more versatile either, but they're applied in different ways so i don't think it makes sense to compare them in that regard specifically)
overall maybe structs are more versatile? but i don't think that matters for comparing them to SOs
right yeah
i just saw that they both store data and in my inexperienced brain that was close enough for comparison
i guess that's fair
i'll definitely have to look this up further
The big value of so is that it’s an asset and not a behaviour tied to a specific scene
like how materials are assets that can be edited in 1 place and used in a bunch of places
But with data you specifically want
Ya
It unity had hindsight and could go back Materials probably would be scriptableobjects
right that makes a lot of sense
since in ror2, items need to carry over between stages
and you need to be shown what you had on the end screen
yeah
and the items themselves don't change in any way other than how much the player has, which is stored in the player
so you can use a scriptableobject to store all of the item's data like the sprite/model (if 2d/3d), name, description and id
then you can control the effects based on how many the player has
But usually you’d maybe have the so for static data to reference and a live instance of something that knows about that so and would have any live changes
well that's not necessarily how they're used
those would be references
the SO means there's only 1 true instance of the item that controls its stats
Same as minecraft having the block in your inventory vs the block placed in world
Depends on how they are used
you would not be instantiating SOs for each item you have in your inventory
ah
so the SOs are already in the scene, you just take their data when you want to use them somewhere else?
so’s are not in the scene
ah
SOs are assets, they exist outside the concept of scenes entirely
mb
U still have to reference them
right yeah we covered that earlier
the data exists separately, when you want to access it you use a reference to the SO
Don’t wanna go too offtopic but for Minecraft absolutely but ror2 i could see a world in which maybe you would have instance them per
ok
just want to recap to make sure i've gotten everything right
SOs are data collections stored as assets that are not affected during runtime, but can be called and referenced from anywhere for their data to be used?
forgive me if i'm misunderstanding, i'm not great at this
ahhh
so would it be a good idea to essentially think of them as universal global variable stores that can be used so long as you give a script "permission" to do so?
They can be affected at runtime, but in editor those changes will persist so it’s recommended you don’t do that
ah
are they used for save data collection in some cases or will i have to come to that another time?
because if you were to change it at all, those changes would persist regardless of the game state
Only in editor
If I update visual is it considered configuration?
Data for objects
Avoid using it for sensitive data like user's score, currency,...
no
it might automatically get fixed, but don't rely on it
actually do the configuration
...instantiating them at runtime?
you aren't supposed to instantiate SOs at runtime
i don't see any reason you'd duplicate SOs for each item in an inventory. that seems like it would completely nullify the benefits
a wrapper class, maybe? but not the SO itself
Depending on the game instantiating can be convenient if you don’t want to spend time establishing some kinda so <-> base class relationship inheritance tree for when you need to edit a lot of those properties at runtime
You'd use the SO as a base and instantiate a class. This avoids confusion between the base SO and instantiated SOs during runtime. Typically, it's used when the same type of item can have different stats and/or modifiers . . .
Its a good way of doing the flyweight pattern, where the SO holds the data that never changes, and the instance non-SO class holds anything specific to the instance
Like an SO class for an enemy for its base stats and other details, while the instance non-SO class has its current health and other state info
It's better to discuss it in practice rather than in theory
What's this got to do with code
What channel i have to post?
Probably #1390346776804069396 if it's about post processing
Done
Hey I have a question, I am making a 3d game where it has a minigame that is supposed to shift the prespective into entirely 2D, with 2D drag drop and things like that.
I'm using cinemachine to pivot from 3D to the 2D look but I'm kinda confused on how to translate 2D things (like ray casts for drag and drop, rendering) into the 3D environment
I haven't really wrote anycode to try and do that I just want to get an idea on how it could be done, if there are tutorials or previews for something like that I'd love to see it
You can just use 3D physics in a 2D space, nothing would break. It's just some extra work over using 2D for an entirely 2D project but it's less work than switching everything over when you swap
I see
I'll try a little demo to see what I can come up with, plenty thanks.
Yep, if you use raycasting to the cursor position from the camera and so on it shouldn't really matter if you are in 3d or 2d.
is there an option to speed up time to debug things which are reliant on light?
most things need light so you can see HAHAHA
can you clarify?
How are time and light related?
oh my god my brain is dead
i made a custom clock for day and night cycle based on time.time but just figured i can just multiple it and stuff is faster
sometimes its just asking the question answering it
I would just add a layer of abstraction so I can manually debug any time I want
can you elaborate
Something like
bool useDebugTime;
int customHourOfDay;
int customMinuteOfDay;
public DateTime CurrentTime {
get {
if (!useDebugTime) return DateTime.Now();
return new DateTime(2025, 11, 15, customHourOfDay, customMinuteOfDay, 0, 0);
}
}```
you can refine this of course, but - layer of abstraction that lets you inject whatever time you want
Or some kind of interface so you can have different implementations
does anyone have some resources on group turn-based combat systems like in assassins creed, batman arkham etc.? ive been banging my head against the wall for like a week straight trying to make one
tbh i might just be too burnt out
I may be missing something but how is assasin creed turn based? Isn't that action rpg?
the combat in the sense of 1 character attacks at a time from a group
i cant remember if its still like that in the modern ones but definitely the case in older ACs
If you are looking for something really turn based this is probably the best course: https://gamedev.tv/courses/unity-turn-based-strategy
<p>Are you looking to <strong>level up your game development skills</strong> and take your projects to the next level?</p><p>Do you <strong>play games like XCOM2 or Final Fantasy Tactics</strong>?</p><p>In this course, you’ll <strong>take your skills from beginner to advanced</strong>, learn to manage and organise a complex project. You’ll c...
not that kind of turn-based unfortunately
If I understand correctly what you want, it probably would be a matter of having a 'manager' that keeps a queue of all the enemies in 'range' and then triggering one at a time to attack. So each enemy would have the code related to attacking, the way he does it and so on, but ultimately the manager would choose who will be attacking.
sort of like that yeah
the problem is that I can understand that system perfectly from a high-level view, but I've written it like 5 times from scratch now and every time it doesn't work
I think it will be easier to start writting it and if something doesn't work - come back with a specific question or problem
at this point I just don't even know what my problem is lol I'm so lost in all of it
I could show an example of what I've got hang on
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
its a lot of code though so if that's too much to help with then I understand
private void FixedUpdate()
{
if (Input.GetMouseButton(0))
{
Debug.Log("Trying to hit smth");
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(mousePos,transform.forward, out hit, Mathf.Infinity))
{
Debug.Log("Hit: " + hit.collider.name);
Debug.DrawLine(mousePos, hit.point, Color.red, 1000000, false);
}
}
}```
Hey I'm trying to use this to raycast from the mouse to try and find an object to hit,
The "hit" works a little too well because just having the object in the camera FOV marks it as hit (and does draw the Hit line correctly)
How can I limit it to check where the mousePos is standing? or not make it work as good as it does
here is what it looks like in-play
so the enemies are not circling, they are not queueing attacks properly
I also just noticed that my LookAt causes them to look up but that should be an easy fix
This is not the correct way to construct a ray from the mouse position on screen.
use:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);```
And do the raycast with that ray.
I suppose u can use layer for this. U don’t have to specify Mathf.Infinity thou
Oh yeah that's how it was in the documentation
I changed it for the very simple reason (that I had Debug Logs off and I though it did not hit anything)
Thanks for the information
actually since I appreciate that this is a rather big thing to help out with, I made a dedicated thread here so as to not spam this chat https://discord.com/channels/489222168727519232/1439323508789215503
Hello, I'm a beginner and I'd like to know where I can learn to code for Unity.
there are resources pinned in this channel
ok thanks
I may be setting this up wrong, but how would I check if an object has a certain script component, and how would I call a function from that script remotely
or alternatively how would I get an object to do something if it hits another object's raycast
Well, show what you've got so far with your raycast
so I created a whole other script called "objectManager" and that's basically what controls health and damage resistances etc
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so I'm not sure whether to have the manager script check for a bullet raycast, or to have this script try and call the manager's damage function remotely
You have the idea there though and it comes down to the hitInfo which contains all the helpful information for where/what the ray has hit
so.. what would I use to return the entire gameobject? cos that's what I'm using to look for whether the object has a manager script or not
And more specifically what you're looking for here is a way to get information of the gameobject that is hit. Usually people will grab the collider information, but you can also get information via the transform. From there you can then use GetComponent (TryGetComponent is objectively the better method so look into that) and checking if it includes the component to access.
So for example:
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/RaycastHit-collider.html
public class Example : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.collider != null && hit.collider.TryGetComponent(out HPComponent hp))
{
hp.DoDamage();
}
}
}
}
}
hell yea
So the idea here is if you hit a collider you know it's a gameobject because it's a component to a gameobject
and from that you can use GetComponent to grab more of those components off the gameobject (assuming those components exist)
hi, my code stops working after the PlayFourth(); , is the logic wrong? https://paste.ofcode.org/34jjtHLYxBb6ny9vxY4ZHmW
....wow...
why are they even separate methods
this could be a loop
uhh, anyways, what exactly do you mean by "stops working"?
idk I wanted to do it like that, that's not more costly is it
what doesdialogueSystem.NextDialogue() do?
cost does not matter in the slightest at that scale
do not worry about optimization here
it plays the next dialogue, you gotta TriggerDialogue(); and then NextDialogue() to play the others
well doesn't run anymore
yeah but what does the method body actually do
are you getting any error messages
perhaps show the method i asked about
it takes the next dialogue asset and plays it with the audiosource, it's an asset made for it
no
show the actual method
https://paste.ofcode.org/cZiQjx5dGuV25JpN3VzuBR , there's another function probably somewhere running in the Update() that works together with it
but I don't think it's something to focus on, the asset is made for it, it's ultra long, there are like 100 scripts and it shouldn't be wrong
if (currentAudio == null || currentData == null || !dialoguePlaying)
return;
so that's a silent exit
try debugging that
see which condition is true there
maybe I should add a debug there to see if it returns null;
ye
even if you assume the asset is flawless, you can still use it or set it up incorrectly and end up with issues that originate inside
this is not blaming, this is going through to figure out what's going on, it's debugging
yes
nothing gets debugged
not sure what you mean by that
well i added a debug here in the if statement and it doesn't get debugged which means the return; doesn't run and isn't the cause of the problem?
what exactly is the code you wrote?
that's a one-line if statement, if you just put another line there then the structure changes
you shouldn't be debugging inside anyways, you should be debugging before
is this wrong?
Its never false checking only returning true
not necessarily wrong, but if you put the log before the if and log both positive and negative cases you can verify that the log works (as in, you saved and it's recompiled etc)
k ill add 2 debugs then
gotta trace through the nextDialogueTrigger thing then probably
also whats calling it to repeat and do a second check?
if playering return, whats calling for a second check after?
wait what? I didn't understand sorry
Based on the first code you are suing a time system to call on NextDialogue right?
yes
the nextDialogueTrigger = true; runs
I've added a debug outside the if statement and it runs
do you know what that means and what might be the issue now? because I initially didn't understand why I had to add a debug outside to be honest, now the issue is probably into the function or code that uses this bool?
okay this is where i could be confused just based on the snippet but whats im seeing is its only called once so if the audio takes over 4 seconds and you have the command being checked at 3 seconds
the code that uses it, probably
I think the way the code works is once I play, trigger a dialogue, it waits for the whole audioclip to be played and then runs the following code
Also i would look into switch statements
for what?
I'm trying to find it now
I know how switch statements work but why would I need that
Lol
Because you have 10 voids for one scene transition and could use that in more then one way
also the code is only being called once
the replacement for all that duplicated code would be a loop, not a switch
loop as well
switches don't really solve anything here
switch is for if functions ??? bro I don't know if you're the issue or If I'm
-# ifs aren't functions
Oh boy.
A loop repeats a block of code, while a switch executes a single block of code based on a specific value. Loops are for repetition and are controlled by conditions like ranges (e.g., for loops), whereas switches are for making a single choice among many possible outcomes (e.g., switch statements). A loop continues to run until its condition is no longer met, while a switch statement evaluates a single expression once and runs the corresponding code block.
Both can work in this.
by the way, how could I use loop for this? should I make a timer That I increase in Update()?
could you show me please how to use it?
you're already using a coroutine
you have duplicated code there
you'd just do something like this
for (int i = 0; i < 11; i++) {
dialogueSystem.NextDialogue();
yield return new WaitForSeconds(timeBetween);
}
```replacing all the PlayNth calls
thank you soooo muchhh, I seee now, I've not really used loops a lot
(this changes the behaviour slightly, but not too hard to fix)
anyway that doesn't fix the issue but yea looks much better and I'll always use them now
also try
{
if (currentAudio == null || currentData == null || !dialoguePlaying)
{
Debug.Log("Nothing");
return false;
}
return true;
}`
}```
this will for sure return a true or false and can be called at any time
Using the return statement in a void method in Unity (or C# in general) immediately exits the method and transfers control back to the calling code. It does not cause the method to "run again" automatically.
...that just doesn't work
you never return any values
in middle of fixing
i hit enter on my own scirpt and sent here
return statement in a void method
that's the behaviour of return in general btw, not specifically in void methods
wouldn't doing that just be important if you return a bool?$
not sure what returning a bool would do here anyways tbh
frr
he is all ready doing it.
no, the method sets a member variable that's used as state
{
if (currentAudio == null || currentData == null || !dialoguePlaying)
{
Debug.Log("Nothing");
return;
}
nextDialogueTrigger = true;
}
} ``` whats the current funcion of his posted code.
it sets a member variable used as state
going of what theyve said already, this isn't even their code
to return a true or flase to nextDialgueTrigger
that's not what return means, no
and if you want to use a return value instead, it'd have to be in the same class or system to be able to update the state correctly
public void NextDialogue()
{
if (currentAudio == null || currentData == null || !dialoguePlaying)
{
Debug.Log("Nothing"); // still playing do NOT play new
return;
}
nextDialogueTrigger = true; // move to next code allow BOOLEAN to be true.
}
..yeah, i can read code
please do consider what classes these methods are in
the calling method and this method are in different classes. if encapsulation is being followed in the asset, the member variable isn't exposed, so it'd be impossible to use a return value to replicate the behavior correctly
I can't find the issue, the script has 1000 lines
I'll try to use multiple dialogues instead and TriggerDialogue() each of them
When a switch statement might be appropriate:
Handling distinct dialogue states or branches: If your dialogue progresses through clearly defined, separate stages or branches based on player choices, quest progression, or other game states, a switch statement can elegantly manage these different paths. Each case in the switch could correspond to a specific dialogue segment or a set of dialogue options.
{
case DialogueState.Greeting:
DisplayDialogue("Hello, adventurer!");
break;
case DialogueState.QuestOffer:
DisplayDialogue("I have a task for you, if you're interested.");
break;
case DialogueState.Farewell:
DisplayDialogue("Goodbye, and good luck!");
break;
}
When a for loop might be appropriate:
Iterating through a sequence of dialogue lines: If you have a linear sequence of dialogue lines that need to be displayed one after another, a for loop (or a foreach loop) can iterate through an array or list of these lines.
for (int i = 0; i < dialogueLines.Length; i++)
{
DisplayDialogue(dialogueLines[i]);
yield return new WaitForSeconds(displayTime); // For sequential display
}
Hybrid Approaches and Considerations:
Combining switch and for: You can often combine these structures. A switch statement might determine which set of dialogue lines to use, and then a for loop could iterate through those lines.
Data-Driven Dialogue: For more complex dialogue systems, consider using data structures (like ScriptableObjects in Unity) to store dialogue information. This can make your dialogue easier to manage and modify without directly changing code. You might still use switch statements to handle different dialogue types or for loops to iterate through dialogue segments within these data structures.
Performance: For the vast majority of dialogue systems, the performance difference between switch and for will be negligible compared to other factors like UI rendering or asset loading. Focus on readability and maintainability.
Ultimately, the choice depends on how your dialogue is structured and the specific logic you need to implement. For branching narratives and distinct dialogue states, switch is often clearer. For sequential display of dialogue lines, a loop is more suitable.
It was the simpliest way to explain my point that i made many times.
respectfully, your point was irrelevant
how is a on point statement irrelevant. his code was no functional
adding a switch would not help there
they were using an external asset for the dialogue - some of the code shown was not under their control or knowledge
While true a switch can still function here. I be it, not the best option but could work. I agree where a for loop is the best option.
yikes, man
again not sure why you are saying yikes.
{
yield return new WaitForSeconds(time);
PlayFirst();
yield return new WaitForSeconds(timeBetween);
PlaySecond(); //calling after 1
yield return new WaitForSeconds(timeBetween);
PlayThird();//calling after 1
yield return new WaitForSeconds(timeBetween);
PlayFourth();//calling after 1
yield return new WaitForSeconds(timeBetween);
PlayFifth();//calling after 1
yield return new WaitForSeconds(timeBetween);
PlaySixth();//calling after 1
yield return new WaitForSeconds(timeBetween);
PlaySeventh();//calling after 1
yield return new WaitForSeconds(timeBetween);
PlayEighth();//calling after 1
yield return new WaitForSeconds(timeBetween);
PlayNinth();//calling after 1
yield return new WaitForSeconds(timeBetween);
PlayTenth();//calling after 1
yield return new WaitForSeconds(timeBetween);
PlayIleventh();//calling after 1
yield return new WaitForSeconds(time);
GoToGame();
}```
```public void NextDialogue()
{
if (currentAudio == null || currentData == null || !dialoguePlaying)
{
Debug.Log("Nothing");
return;
}
nextDialogueTrigger = true;
}
``` If the dialog hadnt finsihed this will return on what ever next call is made
{
dialogueTrigger.TriggerDialogue(); // playded first
}
private void PlaySecond()
{
dialogueSystem.NextDialogue(); //calls check on is something still playing only calls once
}
private void PlayThird()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call
}
private void PlayFourth()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call else this will play next
}
private void PlayFifth()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call else this will play next
}
private void PlaySixth()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call else this will play next
}
private void PlaySeventh()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call else this will play next
}
private void PlayEighth()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call else this will play next
}
private void PlayNinth()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call else this will play next
}
private void PlayTenth()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call else this will play next
}
private void PlayIleventh()
{
dialogueSystem.NextDialogue(); // calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call else this will play next
}
private void GoToGame()
{
SceneManager.LoadScene(sceneName); // game loads
}
that is some insane spam
the majority of it isn't even true
there is no time check inside NextDialogue, what are you going on about
Spam? okay. wow.
real quick, do you know how coroutines work
Do you?
i do, yes. ive used them extensively and have explained them numerous times
public float timeBetween = 1f;
private IEnumerator PlayFirstWhenWanted()
{
yield return new WaitForSeconds(time);
PlayFirst();
yield return new WaitForSeconds(timeBetween);
PlaySecond();
yield return new WaitForSeconds(timeBetween);
PlayThird();
yield return new WaitForSeconds(timeBetween);
PlayFourth();
yield return new WaitForSeconds(timeBetween);
PlayFifth();
yield return new WaitForSeconds(timeBetween);
PlaySixth();
yield return new WaitForSeconds(timeBetween);
PlaySeventh();
yield return new WaitForSeconds(timeBetween);
PlayEighth();
yield return new WaitForSeconds(timeBetween);
PlayNinth();
yield return new WaitForSeconds(timeBetween);
PlayTenth();
yield return new WaitForSeconds(timeBetween);
PlayIleventh();
yield return new WaitForSeconds(time);
GoToGame();
}
``` then please tell me the current wait time on WaitForSeconds(timeBetween)
honestly, no clue what you're even asking
if you're asking about how much time is waited, it could be anything, given that timeBetween is serialized
That was the simpliest question i could ask its in the code.
but that does not mean that each NextDialogue call checks the time and returns accordingly
they are not even called if the WaitForSeconds has not completed
HEY ^ you figured it out
..i figured out that you don't know what you're talking about?
Oh no.
Okay, so let me get this right, let me go slow incase imwrong here. how does waitforseconds work
answer the question
Dude... just look up the docs
Yikes dude
WaitForSeconds is a YieldInstruction that Unity accepts and knows to keep a timer, where - for each frame (aka upon Update, though WaitForSeconds happens after Update in each cycle) the timer is incremented by deltaTime, and once the timer is greater than or equal to the specfied time, completes the YieldInstruction and continues execution of the IEnumerator body of the coroutine
happy?
// calls check if dialogue above was more then public float timeBetween = 1f; NextDialogue will return with no further call
nothing about NextDialogue'sreturnhas anything to do withtimeBetween, or time in general
the time check is in WaitForSeconds, or to be pedantic, inside unity's handling of WaitForSeconds, not in any of the PlayNth calls or in NextDialogue
no clue what "no further call" is even supposed to mean
return inside NextDialogue would not escape the coroutine body, and no throws are involved either
I am. So when using
public float timeBetween = 1f;
IEnumerator Somethinghappens()
{
Debug.Log("Line 1 done");
yield return new WaitForSeconds(2f); // Wait for 2 seconds
Debug.Log("Start line of code 2.");
yield return new WaitForSeconds(timeBetween); // Wait for 1 seconds ( right?)
Debug.Log("Start line of code 3.");
yield return null; // Wait for one frame
Debug.Log("do something after frame passed.");
}
// Wait for 1 seconds ( right?)
not necessarily, given that it's a serialized field
but assuming timeBetween is set to 1, then it's approximately that
okay lets say that an outside force is infact workiong with timeBetween and setting it do dialog length
not sure what dialog length you're referring to there. doesn't seem like the code given accounts for that
^ thats the point. he set it to 1f in the code and could have set it to any number after in the editor.
he then calls this code
public void NextDialogue()
{
if (currentAudio == null || currentData == null || !dialoguePlaying)
{
Debug.Log("Nothing");
return;
}
nextDialogueTrigger = true;
}
``` simply checking if the dialogue has played or still playing.
``` now i dont see in the code where the logic is handled if the above is reading false
public float timeBetween = 1f;
private IEnumerator PlayFirstWhenWanted()
{
yield return new WaitForSeconds(time);
PlayFirst();
yield return new WaitForSeconds(timeBetween);
PlaySecond();
yield return new WaitForSeconds(timeBetween);
PlayThird();
yield return new WaitForSeconds(timeBetween);
PlayFourth();
yield return new WaitForSeconds(timeBetween);
PlayFifth();
yield return new WaitForSeconds(timeBetween);
PlaySixth();
yield return new WaitForSeconds(timeBetween);
PlaySeventh();
yield return new WaitForSeconds(timeBetween);
PlayEighth();
yield return new WaitForSeconds(timeBetween);
PlayNinth();
yield return new WaitForSeconds(timeBetween);
PlayTenth();
yield return new WaitForSeconds(timeBetween);
PlayIleventh();
yield return new WaitForSeconds(time);
GoToGame();
}
``` if this is still going with using what ever time he has in place for timeBetween. if he calls PlaySecond() and nextDialogueTrigger was never set to true due to something still playing this would cause PlaySecond() not to work right?
simply checking if the dialogue has played or still playing.
i don't think so.
from the position, dialoguePlaying seems like it's for the overall state of the entire set of dialogue - if the entire sequence has been canceled, then don't trigger the next dialog
which would be nothing to do with time or completion
keep in mind - it's saying "if dialogue is not playing, stop"
nextDialogueTrigger was never set to true
it was set to true though. he debugged that part and found out
this is my hope. but currenly as he said. the code isnt working. im working with what i have been given and the only thing i could see from the given is if he calls on player#() and nextDialogueTrigger = false then that could be a issue. all i was trying to do was find out how is the code handling if not true so i could help assist and some how we have dragged this out into something.
yeah, not a ton of info was given - thats what followup questions are for, don't make random assumptions lol
I didnt assume anything. I do how ever see why this discord was laughed about in other dev discords. You are very intelligent @naive pawn i think we where arguing for no reason. but assumptions where not made.
because you questioned my ability to code. Nothing i have said is wrong given the little knowledge we have atm. I used the given scirpt to infer that he had timeBetween set to 1. if he did and using code i cant see there could be a issue if he is calling dialogueSystem.NextDialogue(); and this is returning something at a time it shouldnt. again not sure why timeBetween would be 1 but thats all i got to go on. and since the WaitforSeconds(timeBetween) would be using the infered 1 second interval to call on dialogueSystem.NextDialogue() if somehow the other code was still doing something or a audo was not null and or current data was not null and or dialoguePlaying was true then NextDialogue would not make nextDialogueTrigger true and may in this mention other code cause play issues. as the mentioned code has a running timer set to the infered 1 second time interval to call the next void and call dialogueSystem.NextDialogue();
Hello, have been recently learning about how UI is done in Unity:
What I've seen is that UI Toolkit is like the "new, polished" method to make UI, but there are some people that use the Legacy UI objects for simpler stuff. Is this right?
Guys, is it possible to write code so that when I click on an object, my index.html page opens in Google? (On a phone)
you can use Application.OpenURL for links in general, but not sure you can supply a local html file with that
In your code for the objecting you can use
Application.OpenURL(urlToOpen);
^ the local html may be the problem
Beat me to it
UI Toolkit is still in development and there's quite a lot to it that I wouldn't suggest jumping right into it if you're new to Unity. The current UI module (UGUI) works fine for many cases, but it's already hinted at being removed in Unity 7
you do realize that debug info was provided, right
this is just a bad faith argument at this point, i shouldn't engage lmao
What can I use instead? I want a window with a video site with information to open when an object appears.
Yes and he said it was returning true; now on how many of those calls did it return true. did on every cycle of the WaitForSeconds and new void call did it call true or only some times would be my question (didnt see if that was asked)
I mean, if you do web dev and like css/html then you'll love UI Toolkit, but the thing that does create some complication is binding the UI to those gameobject which do require some boilerplate / middleman script
you could have a website that you link to
Meanwhile UGUI you can directly reference (via editor) which does make things a hell of a lot easier
someone knows how to implements vivox
i realy like to pay someone to do it for me
the role game is finished
i tried every thing
i didnt found anything
some can helpme?
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**
would you like to help me? i add your participation
i think the idea is very promising
ou
sorry
i joinned now
i did't read the rules
you should make it a habit to read server rules when joining new servers
so sorry
Mhm! even if I do like the variety of UI elements in UI Toolkit, UGUI seems pretty simple and efficient to work with.
Also, when using UI Toolkit, the whole UI is in a single UIDocument game object. This could make separating UI systems a bit awkward (e.g. health bar, coin count and level progress would be inside one UIDocument object)
Yeah exactly. The referencing is easier with UGUI because everything is an independent gameobject, while your UIDoc would be a single gameobject that you need to open up and bind everything inside of the script
Not the largest problem, but when you compare it to Button where you can bind event directly on the UI to a gameobject script it makes debugging so much easier
Oh, and if you want it to expose properties in the editor, then you're usually making the drawer for it too
You mean expose properties of the UIDoc?
Right, it doesnt expose any properties on the editor unless you make a property drawer
really they need to make this process easier. I'm already exhausted of thinking about it lmao
Hm That doesn't really sound intuitive, thanks for saving me headaches!
Wait a second, I think you can define new UIDocuments and use them as components, right?
So your UI doesn't have to be a single document, even more - you can define your own components so if you need multiple health bars (for whatever reason) or coin counters you can reuse the one you have
Do you mean creating multiple UIDocument objects to separate stuff?
You can have multiple documents instead of one yeah. That would probably be a good idea to keep stuff independent at least
I'm not sure if I would make one for each button per say
Although, if those ui elements interact with each other for sizing and positioning, not sure how that would play out.
I would make one for button component and then reuse everywhere where I need buttons, that way they are consistent everywhere
Yeah true, if it's not a unique button each that would be like some prefab
I should try that idea next time instead of these larger single docs
I think we are talking about slightly different things here - I am not talking about keeping them as separate object in the sense of having completely independent UI elements, it's like regular workflow with prefabs - you define the reusable components but you still put them in one scene or parent prefab (UI). The idea is the same, you are always going to have a level that combines element together - same with building websites, you may have 3 columns in discord but they have a common parent - the page/view. It's completely fine but what's important is that you have the lines e.g. avatar + name + text as a component. That way you can consistently modify behaviour and appearance in one place.
The view is 'using' those smaller components, but it doesn't care about their concrete implementation until their attributes do not change.
I think the closest example is using classes in code - if the signature of the method doesn't change, you can modify whatever you want in the class you are using, and those are 2 different files so 2 different people can work on that at the same time.
In a sense if you did want to go out of your way you could probably remake UGUI button
assuming you want to make the drawer for it
So NOT this, right?:
It can, but communication between those components will be harder. You can make your healthbar and coin count so you can 'drag & drop' them as part of the parent document ui
though you probably could just make ui document properties for those and drag & drop them there, however if it's a large project, long term I would prefer to have something that has a clear component defined. Probably it is time for me to make a youtube tutorial about it. I was thinking about it for a while
Oh! you mean make the healthbar and coin count components that show up here?:
yep, exactly :)
I think that's fine? I think the larger problem is if you do have an independent button inside of a gridlayout doc, which I don't think the prefab idea would work.
but of course can have those elements in independent docs like how those style sheets work and build upon it on that doc
but for healthbar that doesnt need to be contained in a layout then its own doc/gameobject seems ideal
I see. Since I look to work with the UI without tedious workarounds or tight coupling, I'm leaning more towards UGUI, but if the UI Toolkit fits the job better, then I'll try to roll with it!
UI Toolkit is more intuitive that's something I can say for sure. Especially when you start dealing with resizing elements / anchors
anyone know why i get a type mistmatch when i try to drag my player in the scene to a serialized field variable for my enemy in the inspector? people online say you cant do this because your enemy is a prefab but i made this enemy in the player scene (which someone else worked on) its not a prefab. the only thing that wasnt made with that enemy in that scene is the script of the enemy. im referring to class names correctly
an instance of some prefab in a scene can ref other things in a scene just fine
its a problem when you try to on the prefab asset itself.
Type missmatch can also appear if you change the type of a serialized field but it already had a value
Can you show the part of the script that has the serialized property (enemy script), and the class definition of the player class?
The player must have a component (MonoBehaviour class) with the same type (class) as the serialized field (the one you're dragging into) . . .
That's exactly what I think the problem is - that they are simply incompatible types, so I'd love to see the relevant script parts
Exactly. I don't know what "I made this enemy in the scene" means or has to do with it . . . 🤷♀️
The problem sometimes is that you have a prefab and you try to drag an object instance from the scene to the property in prefab - I don't think this causes the same error, but maybe I am wrong. So I think @earnest patio, just tried to explain that this is not what he is trying to do :)
Hi, I have a 3 prefabs metal, wood, axe and I can "wield" each one but when Axe gets instantiated, the children of it doesn't, has anyone had this problem before?
I also need to explicitly set the axe prefab to active or it'll instantiate as inactive
if i have a class BaseSpell and a class FireballSpell that extends BaseSpell, how would i put a FireballSpell into a variable public BaseSpell spell1
in the editor
by using the assignment operator (or drag it into the slot in the inspector if it is a component)
oh wait i forgot to make it an instance 😭
my bad
i always forget i need instances of classes always
Does the axe prefab actually have children?
that + implies the child is an edit of a prefab instance in the scene and not a change made to the actual asset
how did you add the cube child
from prefabs/items
oh forgive me, im mistaking what that + is apparently
I’m trying to drag a game object into another game object’s serialize field. It’s giving me a mismatch. The object with the serialize field in the inspector had its script not made in the same scene.
Hello everyone. I have a problem. I created a game and I'm passing changes through json to the server and from there to the client, but at some point the json breaks and I get an invalid json
System.ArgumentException: JSON parse error: Invalid value.
are you saying that both objects are in separate scenes? because cross-scene references aren't possible. what is it supposed to be referencing if the other scene isn't loaded?
No they are in the same scene
then if they are both objects in the scene and are in the same scene then the object you are dragging into the field does not have the type of component you are trying to reference
I honestly just opted with finding the game object during run time instead of trying to fix it
I’m not able to access unity now but I’ll just give a rundown of what I did: I made a scene. Added a 2d sprite called player and other 2d sprite called enemy. I attached an existing script to the player and an existing script to the enemy. I have made sure their class names are properly set. I go to drag player into enemy then it gives me the mismatch error
What does type of component t mean
what was the variable type
Do you have any ideas about my problem?
considering you've not provided any actual explanation or details about your issue, how would you expect anyone to have any idea about it?
Okay I think this was the problem. Thanks lol
using UnityEngine;
using UnityEngine.InputSystem;
public class DoorScript : MonoBehaviour
{
public Transform mainCamera;
LayerMask layermask;
float speed = 30f;
Vector3 currentRotation;
Vector3 openTargetRotation = new Vector3(0, -135, 0);
Vector3 closedTargetRotation = new Vector3(0, 0, 0);
RaycastHit hit;
float raycastDistance = 2f;
void Start()
{
layermask = LayerMask.GetMask("Door");
}
public void DoorCheck(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
bool isDoorClosed = transform.eulerAngles.y == closedTargetRotation.y ? false : true;
bool isDoorOpened = transform.eulerAngles.y == openTargetRotation.y ? false : true;
if (isDoorClosed == true && RaycastDistanceCheck() == true)
{
OpenDoor();
}
if (isDoorOpened == true && RaycastDistanceCheck() == true)
{
CloseDoor();
}
}
}
public bool RaycastDistanceCheck()
{
bool state = Physics.Raycast(mainCamera.position, mainCamera.TransformDirection(Vector3.forward) * raycastDistance, out hit, layermask) ? false : true;
return state;
}
public void OpenDoor()
{
currentRotation = hit.transform.eulerAngles;
currentRotation.y = Mathf.LerpAngle(currentRotation.y, openTargetRotation.y, speed * Time.deltaTime);
hit.transform.eulerAngles = currentRotation;
}
public void CloseDoor()
{
currentRotation = hit.transform.eulerAngles;
currentRotation.y = Mathf.LerpAngle(-currentRotation.y, closedTargetRotation.y, speed * Time.deltaTime);
hit.transform.eulerAngles = currentRotation;
}
}
Do you know why its not working? I havent really learned how callback works.
Should toss some debug logging to figure out what's not firing
the entire thing isnt working
Like can you confirm by printing to the console that DoorCheck isn't being called, even if it doesn't go into the first statement there
If not then it's something with the input map (not binded correctly or disabled?)
doesnt matter Ill just not use callback
then why bother asking for help 😭
if you want to figure out why something isn't working you need to figure out what specificlly is not working
which is not "the entire thing"
Callbacks aren't bad per say, but going off that second screenshot, this seems rather overkill.
A callback for sprinting? And moving?
It's not like those wouldn't work, but what's the intention?
that's part of the PlayerInput component from the input system
Ah!
transform.eulerAngles.y == closedTargetRotation.y
comparing 2 float like this will give you wrong result, use stuff like mathf.approx insted
approx?
approximate
it compare 2 float correctly
its Mathf.approximately btw
but stll helpful
lemme try this out
when comparing floats i tend to just decide what is close enough for my purposes can subtract the 2 floats get the abs of them and see if its under a threashhold you decide
I tried that before
I just didnt understand how it worked so I gave up with it
its the same, i just use the other cause autocomplete
if (Mathf.Abs(a - b) < threshold) {
dw I know what you mean by threshold
I just dunno how to set it up
more or less how far apart can they be while you still consider them equal
that would be why they just showed you how to set it up..
like i cna say 0.1f is good enough or 0.05f or what ever i need for the purposes of this
you really arent helping at all
what if the rotations are originally in negatives
I'll get a screenshot of my old code rq
nvm
Idk where it is
alright
it works
buuut
its checking the player rotation not the doors
fun
That's what I said the issue was here: #💻┃code-beginner message
hey i need some help the world ui is not displaying behind my player or objects do i need to add sorting layers Maybe
Say you have 10.5 - 10 = 0.5, there's a decent difference here, meaning if your "threshold" was 0.1, then the condition if (0.5 < 0.1) would be false, the two numbers aren't similar
However if (0.00001 < 0.1) is true, indicating the numbers are similar
Often floats will never be perfect whole numbers, 10.00000032 10.00000047. for all intents and purposes, you can just think of them as both being 10, but to a computer they aren't the same. You would always get false if you directly compared them
anyone know what might be the issue with this? I'm trying to scale the tree when it's been hit but it's not reflecting in the game scene
while (t < popDuration)
{
t += Time.deltaTime;
var popAmount = popCurve.Evaluate(t / popDuration) * popIntesity;
transform.localScale = startScale + Vector3.one * popAmount;
yield return null;
}
But subtracting them, and having a threshold like if (0.00000015 < 0.001) you can basically ensure that "similar" values will be considered the same
using UnityEngine;
using UnityEngine.InputSystem;
public class DoorScript : MonoBehaviour
{
public Transform mainCamera;
LayerMask layermask;
float speed = 30f;
Vector3 currentRotation;
Vector3 openTargetRotation = new Vector3(0, -135, 0);
Vector3 closedTargetRotation = new Vector3(0, 0, 0);
RaycastHit hit;
float raycastDistance = 2f;
void Start()
{
layermask = LayerMask.GetMask("Door");
}
public void DoorCheck(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Started)
{
if (RaycastDistanceCheck() == true)
{
bool isDoorClosed = Mathf.Approximately(hit.transform.parent.eulerAngles.y, closedTargetRotation.y) ? true : false;
bool isDoorOpened = Mathf.Approximately(hit.transform.parent.eulerAngles.y, openTargetRotation.y) ? true : false;
if (isDoorClosed == true && RaycastDistanceCheck() == true)
{
OpenDoor();
}
if (isDoorOpened == true && RaycastDistanceCheck() == true)
{
CloseDoor();
}
}
}
}
public bool RaycastDistanceCheck()
{
bool state = Physics.Raycast(mainCamera.position, mainCamera.TransformDirection(Vector3.forward) * raycastDistance, out hit, layermask) ? true : false;
Debug.DrawRay(mainCamera.position, mainCamera.TransformDirection(Vector3.forward) * raycastDistance, Color.yellow);
return state;
}
public void OpenDoor()
{
currentRotation = hit.transform.parent.eulerAngles;
currentRotation.y = Mathf.LerpAngle(currentRotation.y, openTargetRotation.y, speed * Time.deltaTime);
hit.transform.parent.eulerAngles = currentRotation;
}
public void CloseDoor()
{
currentRotation = hit.transform.parent.eulerAngles;
currentRotation.y = Mathf.LerpAngle(-currentRotation.y, closedTargetRotation.y, speed * Time.deltaTime);
hit.transform.parent.eulerAngles = currentRotation;
}
}
More code to fill your screen! And a video!
Just watch the video for an awful explanation but a visual representation
(what is the problem you are looking for help with)
its not opening fully
Well, one problem with your code is you're trying to lerp but this is a one-time event
You probably want some coroutine inbetween it all
otherwise some update logic using states to specify opening and closing
can you show me what you mean?
Does anyone know any good FPS tutorials with the input system? im pretty new FPS movement so I think it would be a great help
just learn the input system alone, what does fps matter?
Fair point
Also, Googling "Unity FPS New Input System" will yield tons of results . . .
Did you add this script to the wrong child object? I see the mesh collider changing scale
don't think so
I added it to a tree prefab I found in the asset store
Im out in a minute, but what I'm trying to say is you have methods there which are supposed to be called over multiple frames for it to open/close over time, but this interact method is only ever called once. However, if you don't care about it opening/closing slowly and don't mind if it's instant then you'd probably want to look into other methods of rotation.
I think it's not scaling because it is marked as Static
ohhh ye that might be it
yup that was it thanks
hey hey everyone, how are you ?
I was using normally my Unity now, and suddenly after weeks using without a problem. My underlines red is not workig, and the AI inline that helps me complete things also not working. Any ideas?
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Also, wdym by "AI inline"?
hey there, i followed this tutorial https://youtu.be/dcPIuTS_usM?si=hLK-v7InA-SsB6aa to make a dialogue box with choices. But how do i make it where if they choose a certain choice, smth in the game also changes rather than only the text.
ex: if the player gets the question wrong, they lose one life.
The video utilizes the dialogue asset so i dont know if its possible, thank you!
In this Unity game development tutorial, I'll show you how to create a dialogue system with choices using Unity's built-in tools. This interactive system is perfect for creating immersive games with branching narratives.
Whether you're a beginner or an experienced game developer, this tutorial is a must-watch for anyone wanting to add a dynamic...
The video doesn't use any assets but you can put whatever code you want in the SelectResponse method that's called when the player makes a choice
(probably intellicode)
How do I get this dialogue asset? I can't seem to find it in my unity version
You make it yourself. The entire video is about making it
Yeah my bad, shouldve watched the video carefully
did not know u can make ur own assets in the files
Its quite a nice feature of Unity, another handy thing is you can add things to the top row of the editor (with the File, Edit, Assets... row), like this:
[MenuItem("MyThings/HelpfulStuff/Do Something")]
static void ReloadDomain() {
EditorUtility.RequestScriptReload();
}```
Oh wow thats so cool, thanks for telling me
I have a joint object anchored to a target object. Then I have a camera following that joint object.
How can I make it so that I clamp the camera on the local x relative to the target and also make the x an absolute value?
It would be easy if it were parented to the target but I shouldn't do that for the joint
if you have a for loop within a for loop and use break, does it break outside of just the for loop break is in or out of both of them?
That should be pretty easy to test yourself but it only breaks the loop it's in
ok sweet ty
to expand - just as a rule of thumb, flow control tends to bind to the innermost thing
if you have if (...) if (...) x; else y; the else will be bound to the inner if
returns, breaks, continues, yields will be for the innermost relevant construct
ok cool I assumed as much
some languages have labels to be used with break/continue and/or goto as well
is it really useful in c? one of my lecturers once told us if we were ever to use goto in an assignment, he would find and jump up and down on the offender until they stopped using it
it's pretty useful
it's easily overused though
so if you don't have the experience to use it well, avoiding it altogether would probably be better
I agree it's useful, but the reason given was that there's no way to tell what part of a function the goto was used in if there are multiple
It can be used for re using cleanup code in a function
ides exist
this is simply false
no i mean for the program to tell
it's hard to read at a glance sure, but if it's hard to trace with a little reading? that would be overusing it
- the program can tell, it's called static analysis. compilers wouldn't be able to work if they couldn't tell
- the machine code doesn't care anyways, it's all just jumps and branches
hey i have an issue
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
i am trying to make my gameobjects glow for aesthetic
i am trying to use post-processing but it doesnt work
how sure how that's a code issue
ask in #1390346776804069396, and provide some details about the issue (specifically, describe how exactly it isn't working - no result? wrong result? errors?)
From what I remember of the conversation I had with him after the lecture (it's been a little while) I think he meant more that it could very easily lead to logic errors in the program.
It might be relevant to note that this was a class specifically based around designing algorithms in C, so manual memory allocation/deallocation and general control over what state all variables in the program are at at all points was heavily focused on.
Anyway, I know that in general goto's aren't forbidden, but I was still under the impression they were bad practice
I think he meant more that it could very easily lead to logic errors in the program.
i don't see how that relates to "for the program to tell", but yeah, that is true - that would be a case of misuse though
gotos aren't bad practice, using them wrong is bad practice - but it's easy to use them wrong, so they may as well be bad practice if you don't have experience yet
that applies to a lot of things, actually...
practically all uses of goto are wrong and unnecessary, this is often simplified to goto == bad, using goto to break nested structures is the only real usecase (single exit cleanup) and should only come up in multidimensional iteration. Though even there it’s not strictly necessary.
That might not have been the exact right wording, but I think what he said was, if there are two goto statements that go to the same place, there isn't a (non-hacky) way for the program to know which goto statement was the one that got hit
Example:
if(condition) {
//code
goto position1
}
else {
//code
goto position1
}
//later down the line
position1:
//more code
Though I'm not exactly sure, since as I said, it was a while ago.
I do think that after looking back on it, that was most likely to prevent semi-beginners from getting used to using it wrong.
oh, yeah that's true. but if you have something like that you wouldn't care where it came from
I did end up asking about this specific usecase, but was told specifically to also not use goto then - but I think that was just to get me to avoid getting used to using goto's in other situations
otherwise you could have some sort of state variable. wouldn't consider that hacky
honestly from the sounds of it - he's making valid points but also exaggerating to dissuade usage
Likely. The whole idea of structured programming was invented because goto is such a mess.
The badness of goto cannot be overstated. You may be able to live with it if only you will have to touch the code and you use it in a strong structured way by convention. As you would when writing assembly
it definitely can tbh
"gotos, even implicit ones - anything that turns into a branch or jump instruction is bad. code should be strictly linear"
That’s not about Goto specifically, that’s about branching in general
aw cmon, let me have a little room to be creative. otherwise it'd just be "gotos are the work of the devil and anyone who even thinks about it deserves a death sentence"
at the end of the day structured constructs are implemented via goto. structured code that uses goto is the bad thing, not goto used to create structure
I think using goto in c# is bad because we have many language features that are better suited
In C its a different story.
If you're using a lot of malloc and realloc, is there not a potential for the code to need to know whether a certain pointer was reallocated or not when coming out of a goto with multiple entry points? I know that's just bad programming, but it's technically a situation where you would need to know where it came from right?
the code doesnt know anything. you'd use goto to specifically ensure manually allocated memory is freed
Well, in C you largely only know what track manually.
If I was a beginner and ran into people talking about malloc on a beginner channel I'd probably run screaming for the hills.
why? It is a beginner topic.
funny joke
I don't really know you well enough to know if you are joking!
Do you assume that all beginners must use modern high level language that hide the actual basics of programming?
I mean I've learnt malloc and realloc and I'm still a beginner in both C and C# by any definition
I don't want to get into drama, but it is the Official Unity Discord.
people asking for help here hardly know any c#
so yea its not fit for here but people refuse to use code general 🤷♂️
in the context of the unity discord? yeah?
I got this Theme SO that is used as addressable to pack my theme data. The PrefabList is supposed to contain segment prefab references that will be picked randomly to be spawned.
It works fine, but I'm wondering if I'm overusing AssetReference here. Since async operation is quite costly, should I switch back to just normal references? What are the exchanges?
{
[System.Serializable]
public struct ThemeZone
{
public float Length;
public string Name;
public AssetReference[] PrefabList;
}
[Header("Objects")]
public ThemeZone[] Zones;
}```
the point of asset reference is to not have direct dependencies but also be more flexible than specifying an address.
use #📦┃addressables in future
(another example of non beginner topics in this channel)
I saw someone in a music context once say that the problem with tutorial-based learning (rather than something like one of the pathways on learn.unity.com) is that you end up with a musician who can't play C-major asking about phrygian dominant.
not throwing shade at you @hot wadi though. Your question made me go look up an aspect of SO's that I didn't know about.
if your goto jumps across an allocation/free, it's definitely badly placed
Yeah I think that's probably what was being referred to
Also, making students use breaks and other methods instead of just gotoing out of a nested loop is proably better for learning
just plain function calls and matching arguments -- what you pass into a function as in '3' and '4' in sum(3, 4) with formal function parameters -- as in 'x' and 'y' in public int sum (int x, int y) and then sorting out what is returned... that's probably overload already. I remember types being not that fun as a beginner.
-# uhh, is this in relation to a previous message? im kinda confused
oh sorry. I sort of took a cognitive leap from goto, and breaking in and out of loops to something more basic.
I wasn't flexing... I'm legit remembering what was hard as a beginner.
oh yeah no i don't have an issue with it, i was just confused which message it was meant to reply to lol
I think direct dependencies are ok in this case. Once I load the theme, the prefabs contained should be ready to be used
why are you replying to them 😆
it's over my head. My quick read is that async loading is either for huge projects where you are managing memory, or probably even more to the point network calls.
Ah, yeah, sorry wrong reply
the general theory (again to keep it beginner friendly) being that when you request a resource over the network you can't just halt all progress and wait for it to come back, you have to basically say "when this resource is ready, call me back and we will handle what you loaded"
(that's a lot of reply from me for being the wrong recipient of a message though! sry! )
what is going on
for (int j = 0; j < myList.Count; j++)
{
if (myList[j].TryGetComponent(out MyType myType))
{
myOtherList.Add(myType);
}
}
``` i have this being red highlighted in vs with suggestion to invert the if ``if (!myList....){continue;}myOtherList.Add(myType);`` why is this "better" ?
that suggestion seems a bit aggressive here, but if you were doing multiple things inside that if statement and nothing else was happening after it, then a guard clause would make sense for readability
what's the message on the highlight, exactly?
Not neccessarily "better"
oh, i misread as it being !myList, got real confused there for a sec lmao
this red highlight bothers me, ill just follow the suggestion
red would be an error, no?
no not an error message, the code is being highlighted with "Expression to evaluate" if you hover
Ugh, why does my Unity license keep disappearing? This ish is annoying . . .
@avc Think of a loop like a function call in the sense that the loop should really only have one responsibility. If that responsibility is processing this newly found (or not found) object, you continue out of that iteration right away if the object isn't found.
ah, that looks kind of like a weak warning
that's not what the suggestion was about
i followd the suggestion and the highlight persist, now suggesting the prev arrangement. wtf
explain?
the suggestion was about a guard clause, not responsibility
It's just suggestion. Unless u are getting real compiler error, u should keep it simple
Yall know any tutorials or guides on making 2D physics from scratch, as in without rigidbody?
I tried multiple times and there's always some weird thing that messes up.
At least collisions limited to static objects, entities in my game don't usually interact with anything besides triggers and static surfaces
fun fact, but it is apparently more expensive to move a 2d collider without a rigidbody than it is to move it with one
There is "Game Physics Engine Development" by Ian Millington ISBN 978-0123819765
i have to find the source that went in depth on it, but the gist is that the collider is basically recreated each time it is moved if you aren't using a rigidbody (at least for 2d, this likely does not apply for 3d)
i think ive heard that for 3d as well
it gets deleted and recreated in the physics scene, rather than getting moved
Hey, I'm trying to learn the "new" player input and I am having problem to change directions with Pitch and Yaw by using mouse as the controller. is it not the basic one to have the binding as delta (mouse) because it doesn't seem to work even though mostly everything is connected
how exactly does it not work? what's the issue you're having? (actually, perhaps move to #🖱️┃input-system)
So for instance I want to make a square that can move left and right and jump, while stopping by collision with static object.
WIll this (if this is what you meant) teach me how to do that?
#🖱️┃input-system and show more details about your setup
it teaches you how to make any kind of physics based on well understood principles.
oh sorry didn't see that section, will post there
Caveat on custom physics: you should be able to point to a measurable/provable issue that requires a custom engine/system, otherwise you're likely reinventing what Box2D/PhysX give you. You still have to live with the same problems that they have, you can just apply more constraints and optimizations.
here is a source from one of the people responsible for the implementation of Box2D in unity
https://discussions.unity.com/t/does-a-moving-object-with-a-collider-need-a-rigid-body/1488747/11
Usually you can extend the existing physics system with your customizations
also fun fact, but in the 6.3 beta there's a new low level physics api for 2d if you really want a custom(ish) solution without doing everything 100% manually
I'd say the one exception to this is to do so as an intentional learning exercise
naturally
Yeah I wanna know more about game physics in general
that's the reason behind my question
one unfortunate thing with learning projects that tackle really tough problems: they rarely get to the interesting/hard bits (due to time/cost)
but even a general awareness of the problems and theoretical solutions is very valuable.
hi, I was wondering if properties mess up serialization and therefore the ability to save games, and if so what the solution is (not using properties for data which needs to persist?)
this depends on the solution you are using to serialize data to save to disk. what are you using?
erm, nothing right now, I am just learning about how saving even works
This question is way too vague.
the unity serializer for json wants fields that fit the normal unity rules
You need to just follow the rules of whatever serializer you're using
some of them work with properties, some don't
oh okay I'll just look into what serializers there are then
well, properties don't really store data at all, they define how data is retreived and replaced
you still need a field to actually store the data, and in the case of something like float x { get; set; }, there's a backing field automatically generated
Just code libraries that take objects and convert them to a serialized form, like text or binary, that can be written to a file
jsonUtility follows the same serialization ruleset from what you see in the editor
normally objects in memory are sort of strewn wildly around in RAM
serializers put everything nicely in "serial" order, so they can be written cleanly to a file
yes I was wondering if I should follow the general C# advice of writing at least an autoimplemented property for everything, so I can add validation later without changing much
are you saying you're trying to serialize auto properties? That's not something you can even serialize in the editor without specifying the backingfield
hmm so I'd have to actually write out the backing field too then?
that's okay, just a bit more text
[field: SerializeField] public int value { get; private set; }
Hey, i have the Problem that if i code the "Global Audio" my Game does not function i have this code from the Docs. gived him the References but still it does not work for me.
what exactly doesn't function?
ok, so not a code issue
okay, so it must be the Audio Mixer
did you route the audiosource through the respective mixer?
if you can't figure that out, continue in #🔊┃audio
I want to make a system where, when the player does a specific thing, they get XP, and for every 100 XP, they get 1 Point.
what would be the best way to code this type of system in non-Unity 6 versions? I was first thinking of making it function with a threshold, where a hidden variable is added to with gained XP until it reaches 100, at which point the hidden variable is reset to 0 and the player is given 1 Point.
The problem with that, however, is the possibility of getting more than 100 points at once, which could cause the rest of the XP to be wasted, or not give Points at all...
oh, I see. so its just reducing by 100 instead of resetting to 0?
or,
points += xp / 100;
xp %= 100;
hmmm, I haven't actually used the %= thing before...
(assuming xp is an integral)
it's the same idea as += or -= or *=
a •= b -> a = a • b for arithmetic/bitwise operators
% itself is the modulo/remainder operator
Hi, how can I make a map like this, that shows when I click space, and it possible to rotate/zoom in with the mouse?
split it into smaller problems, and start by googling/researching
Mm
- make make map
- show on pressing space
- add rotate w mouse
- add zoom w mouse
Personally id guess its masking and moving a sub image in a world space UI.
also from a design standpoint it feels like a horrible way to handle a map 🤔
it feels like what far cry 2 did just overdone
but thats all it is tho is a rotating world space UI element i believe w/ masking
and no attempt to hide the lack of tiling on the map itself
and tacky nothingness of a border
jinx or whatever
the white behind it is gross 🤮
i've been meaning to make one in all honesty
more like an iso holographic map that does the same thing..
-# (its basically the same mechanics you use for a top-down pannable game, like map scrolling, panning, zooming etc )
is there a way to cancel an Invoke() under a certain condition? I want to make my reload sequence interruptible if the user is still able to fire.
i was imagining something like the division 1 trailer map
when you said holographic
where the map just appears on the ground around you
thats also nifty im probably gonna try doing that honestly
CancelInvoke(); no?
didn't know that exists
where did you find invoke
out of curiosity
it was one of the things I learned from a shitass tutorial
which I would advise against watching because apparently the code bro writes is utterly horrendous
yeah makes sense
generally you just wouldn't used invoke like ever tbh
Coroutines are what you'd be better off using and what you'll find better resources on online
a big benefit of them for this specific problem is you can store the actively running coroutine and cancel them specifically
https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Coroutine.html
the examples in the doc here convey how to use them pretty well
You see that it shakes a bit when you move, is that possible to implement if it is a ui?
so i have some text inside a panel, but if the aspect ratio changes by a large amount then the text ends up too big for the box, any idea how to fix that?
Correct the anchors for the text and use the "auto size" setting on your tmp text
you could use a content size fitter or something i believe
ah cool.. gotcha
so it stays in the box now but why does the box get so stretched?
its anchors probably
welcome to UI
is that how your supposed to put the anchors?
thats why razor is peak
that wasnt listed on the channel list
i love discord hiding channels
i dont think thats how that works
it hides channels based on the questions you answer when you join
yeah, they just started doing that with the new channels.
wow thats really annoying
and I swear the tab to enable the channels is buggy at times and the UI breaks
i cant scroll through the browse channels thing because it keeps jumping around
i think because the channel descriptions are too long
Hah yeah its harder to remove 🤣 unity UI has a tendency to lag a frame behind in world space.
so ive got a script for switching scenes its just
using UnityEngine;
using UnityEngine.SceneManagement;
public class SwitchScene : MonoBehaviour
{
public string sceneName = "MainMenu";
public void NextScene()
{
SceneManager.LoadScene(sceneName);
}
}``` and i was thinking instead of typing in the scene name, could i just set the public variable to be the type Scene and then just drag a scene into it in the inspector
but it doesnt seem to work
I've created a client-server on a pure tcp protocol, and now I want to transfer its creation to netcode for game, but I'm facing a misunderstanding. Let's say I can send a value through sertverRPC and clientRPC, but I don't understand where it will go and so on. So, should I store a copy of the server class on each client to access the server's methods?
like how you can have a different object linked up in the inspector
You can't drag a scene in no
you would have to type the name
the inability to serialize a scene reference is a long-running frustration in Unity.
So it should be like this?
most network frameworks have some kind of "NetworkManager" object that handles dispatching and receiving remote procedure calls (among other things). They also often allow you target your RPCs towards either particular connected clients, towards the server only, towards all connected clients, etc.