#💻┃code-beginner
1 messages · Page 196 of 1
There are several ways to get input.
check for a specific tag when it collides maybe? or use collision layers
They made it like this.
I did like onDisable
i did use a tag
but it ignores that the children has got another tag
Yes, you tend to use both of these styles together
The former makes sense for non-buttons
things that don't "happen" at a specific moment
The latter makes sense for buttons
you want to do something in response to the Fire action being performed
Im just confused a bit how everything is called what is better and what is corect
First one you call manually somewhere in like update or something
Second one is sort of callback that will automatically get called when that button gives some sort of input
oh thanks man minor mistake again. this part is alittle hard and overwhelming sorry
i'd search on google why that happens and maybe you'll find a solution
So second one is better considered it wont get called constantly?
Again as fen said, both are used together usually
I use both.
Vector2 moveInput = moveAction.action.ReadValue<Vector2>();
Vector3 worldMove = entity.transform.TransformDirection(new Vector3(moveInput.x, 0, moveInput.y));
Vector2 lookInput = lookAction.action.ReadValue<Vector2>();
lookInput += gyroLookAction.action.ReadValue<Vector2>();
I use ReadValue for things I need values from every frame
foreach (var actionRef in callbacks.Keys)
{
actionRef.action.performed += callbacks[actionRef];
}
I subscribe to the performed event for things that I need to run a method in response to.
It's alright happens all the time to the best of us haha
Can you explain to me how did you store values in there xD
I'm mindblown
callbacks is a :
Dictionary<InputActionReference, System.Action<InputAction.CallbackContext>> callbacks;
actions.Add(walkAction);
actions.Add(crouchAction);
actions.Add(runAction);
runs in Awake
I just did this because I didn't like the repetitive subscribe / unsubscribe code
Ahhh lmao
I'm not using the PlayerInput to directly call methods
just InputActionReference fields
How do you get rid of an "unwanted action" in this method??
i don't understand what you mean
Say you don't want to subscribe to crouch anymore in following builds
then I'd remove it from the dictionary
Wouldn't actions get messed up?
oh, I just noticed that this was the wrong code lol
callbacks[interactAction] = Act;
callbacks[discardAction] = Act;
(the method looks at the action that triggered it to decide how to handle the input)
actions is just a List<InputActionReference>
everything in that list gets enabled
and everything in callbacks is used to subscribe to events
i should probably just get rid of that...i added another system whose job is to correctly enable and disable input action maps
Ahhh got it, makes sense now
i shouldn't have anything enabling individual actions
I'll probably still stick to my caveman ways as it's easier to read and ignore but cool to learn new ways 
` Vector3 followPositionPlayer = Vector3.Lerp(transform.position, physicsPlayer.position, Time.deltaTime * menuFollowPositionSpeed);
Vector3 followRotationPlayer = Vector3.Lerp(transform.eulerAngles, physicsPlayer.eulerAngles, Time.deltaTime * menuFollowRotationSpeed);
Vector3 followPositionHead = Vector3.Lerp(transform.position, physicsPlayerHead.position, Time.deltaTime * menuFollowPositionSpeed);
Vector3 followRotationHead = Vector3.Lerp(transform.eulerAngles, physicsPlayerHead.eulerAngles, Time.deltaTime * menuFollowRotationSpeed);
transform.position = new Vector3(followPositionHead.x, followPositionPlayer.y, followPositionHead.z);
transform.eulerAngles = new Vector3(followRotationPlayer.x, followRotationHead.y, followRotationPlayer.z);`
can someone help me fix the euler angles lerp please
it snaps weirdly
and when i tried quaternion lerp it didnt work
and what Ive realized is that I wrote this code and thought made sense (I think it does) this code is for destroying animals if their position is greater than...
but what Ive realized is clones of prefabs Z value dont increase or increase very little amounts
even though they are very far away
Define "snaps weirdly"
like if it rotates past 360 degrees it like starts rotating backwards
What you see in the inspector is local position. Your code is checking world position. Does this object have a parent
yes. the parent spawns the children
it is prefab
What position is the parent at
I mean the parent of the object that you say doesn't move much in Z
this?
spawnmanager spawns clones of this
im not sure if its like parent and children
I use this code to call them
You know what nevermind I've decided I don't care
I don't have the patience to play 20 questions with someone who doesn't understand what I'm asking
I'm too tired today
thats deep
yeah
I didnt assing any parent or children so I didnt quite get what youre asking for
this is the best I can show you
That's the child, which is a local position
See the thing right above the thing you circled on the left
That's the parent
Wait, maybe i'm wrong
I can barely read anything with that color
can somebody help me change the vector lerping to quaternion lerping pls
Ok yeah, that is the world position
i tried and it didnt work
Fox(clone)
down arrow
SM_fox_01
sm_fox_02...
you said you couldnt read so I wrote what wrote there 😄
okay didnt see that
THIS one is a child though
#💻┃code-beginner message
The sm ones are children of the prefab it looks like (as you showed with the fox)
So it's local position
To be clear, the things with a down arrow are called parents (if collapsed, it's a right arrow)
Understanding the Transform hierarchy is very important.
It's fundamental to how your objects are positioned in the scene.
The relevant point here is that, if your parent is scaled up, a small change in your local position results in a huge change in your world position.
If your parent's scale is [10, 10, 10] and your local position is [1, 2, 3], your world position is [10, 20, 30]
the concepts of transforms, parent objects and child objects also carries over into DCC apps like blender and maya as well, pretty much anything with 3d and a lot of 2d things as well
(assuming that the parent is not rotated and is at the origin)
here instead of && i used || and problem fixed
I also tried local.transform
instead of transform
but that didnt do much
it sounds like you just tried random changes until it kind of worked
did you read anything we wrote?
You just need to look at the parent transform
what does ForceMode.Impulse do
I read all of them
links too fast 
it describes all four modes
If you misunderstood anything, let us know. Because nothing you tried makes sense based on what we said
no i need a quick summary of one sentence on to what it does
Adds force to a rigidbody in a way
is there something wrong with the descriptions on the pages
well yeah but I didnt wanna ask more questions because I asked way too many already
im just not reading allat
I should point out that the second page I linked, indeed, has two-sentence descriptions
sigh
2 times more than im willing to read
in what way
Then programming is not for you. Good luck
this is ridiculous
In a way described by the links fen sent
put down your phone and read a single page of text
all im understanding is that it makes the force happen faster
There ya go! 🎉
huh.
You read it and figured it out sorta
it's all you're going to understand if you don't read the documentation
i did
what is dt
DeltaTime
so impulse is just removing framerate stuff
no, it is not "just removing framerate stuff"
thats what im seeing
it applies an instantaneous force to the rigidbody
then you should try reading the words on the picture instead of just the code
doesnt seem very instant to me
why does this happen, I'm very confused?
is just using force making it accelerate or something
Seeming and being are two different things
ur using names you probably shouldnt use
Hmm okay I see
how to quaternion lerp on two axis please
euler didnt work
But why would it care?
show the full code.. i think its just out of place
outside the code block
Show all of the code
without the big popup getting in the way
Don't ping people you are not in a conversation with please #📖┃code-of-conduct
the entire script would be ideal
mbmb
First of all, though, never multiply by deltaTime in lerp
https://unity.huh.how/lerp/wrong-lerp
public class UIPopupTrigger : MonoBehaviour
{
// Start is called before the first frame update
private bool IsTriggered = false;
private GameObject Trigger;
private GameObject CursorText;
private DetectArea PopupTrigger;
[SerializeField] string text = "Press E to interact";
void Start()
{
Trigger = transform.Find("proximity").gameObject;
Trigger
CursorText = GameObject.Find("GameManager/GameHUD/Popup/CursorText");
//textmeshpro
CursorText.GetComponent<TMP_Text>().text = text;
CursorText.SetActive(false);
}
}
oh, that's just because you haven't written anything more
well if u just put Trigger out in the open w/ nothng ele it'll error
Trigger is not a valid statement
If you delete the unfinished line, do you get an error on the actual line before it
finish the line 😉
it's been left hanging
ik abt that but it doesnt have to be perfect
Does it have to be functional?
alr ill change it
but im js tryna figure out the quaternion problem
bc it doesnt work at all then
Well the dt was part of the problem I bet. But I suck at rotations.
Is there a reason you chose lerp other rotation methods though?
Quaternion.RotateTowards will steadily rotate towards a target.
it looks nice
The whole code is wild honestly, not sure what the goal even is
yeah icl
im restarting
I'm attempting to make a maze generator that can choose from different Node prefabs, the generator works, I'm having trouble selecting a random Prefab to use for the maze
Your types don't match.
prefabChoice is an array of GameObjects
But you're trying to store the instance into a MazeNode variable
Perhaps you meant to have an array of MazeNodes?
If you instantiate a component, Unity copies the entire game object
Yeah i just clocked actually thanks so much
cant believe I made that mistake
to be honest I didnt think you could make a list of objects that derive from a class so easily like that
you can make an array of whatever you want
ended up getting an error telling me that the object i wanted to instantiate was null but it fixed itself somehow
there's nothing special about GameObject
you may need to re-assign things in the inspector
- GameObject[]
+ MazeNode[]```
fancy
Hi so I can't seem to figure this out, I have a robot arm with two bones and it needs to calculate the angle at which the bones have to be in order for the end of the second bone to end up at a target position, but I have no idea how to approach this
Preferably while rotating on only one axis
i was trying that but I can't get it to work right, it either messes up completely or ends up on the completely wrong position, or uses multiple axis
Feels a bit dumb to ask but.. how would I define what axis it should rotate on 😅 as I need it to do it in 3d space but only on the local x axis
transform.rotation = Quaternion.AngleAxis(30f, Vector3.right);
would rotate 30 degress around the x axis
oh now its a much more complex question
yeah 😅 i have been stuck on this for a few days now
I would suggest making the most basic IK setup possible
I dont really use builtin IK but the axis would probably be your limb's "right" axis (often transform.right) or a cross product of the two limb's directions wont work if the limb is straight
Some IK rigs have a polar bone, which dictates towards where the bend is directed, but I don't know if Unity has support for that built-in
I imagine it's different in 2D
oh wait, this is in 3D, isn't it?
Yes it's in 3d
I'm not sure I got that in my head, sorry
No problem haha
2D IK won't help you here
ok that's what I assumed, but worth a shot I suppose
I had a working IK setup before but I couldn't get it to work with constraints
I mostly use FinalIK, which is third-party. I need to give Animation Rigging another go
FinalIK is 90$ 😭
Yep. It works real nice, though!
Gimp 😄
no idea I came late
Ah ok, it has nothing to do with this
yes, we're talking about inverse kinematics
wait for a sale
I managed to solve my problem 🤠 package called Animation Rigging
Yeah its good one
buggy but getting ok
Yee got it working with what I want so I'm happy 😊
https://gyazo.com/ba7662e96de399ecddf4c6adeefa3b57
Instantiate returns a reference to the instantiated object. so you use that reference to access any public members
I don't understand what you mean by that.
that's too bad. you didn't bother showing code so i cannot suggest any other info 🤷♂️
the fuck
variable = instantiate(etc)
then reference variable (if i remember correctly)
Here's the code: https://pastecode.io/s/xp91ias7
brother discovered an if statement and used it everywhere
Whoever delt with Unity FPS assets on player controller. How does it read movements and presses?
It's wild how much better the formatting is, and yet still so horrific
I formatted it!
you have been told time and time again that you need to fix the formatting for your code. i'm sure you've also been told at least multiple times that you should be sharing your code using a site that adds syntax highlighting because that terrible formatting + lack of syntax highlighting makes that entirely unreadable
Kinda, a little
I formatted it! Honest!
AHAHaha
It was worse?
And my teacher complained that looking into my code was bad
I remember what it was before. And yes, this IS different, and slightly better. But it is still so far from what it should be
your configured IDE should be able to format it automatically with just a couple of key strokes
This is unity asset player controller. How does it get movement and other things? I cant find references to inputs?
Yeah that one is tame. One time it was like this, but without the indentation
you accidentally a bit of your link
:/
make sure you've selected the save button on there. or use a different site if you cannot get that one to work
it's a good thing there was an entire second half of that message with an alternative suggestion
why wont it accept he script?
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I think I found it, its directly accessing inputs huh
it uses the Input System with the PlayerInput component to get input
yeah it just does it differently from what I got told
Also it has this bait
a powerful website for storing and sharing text and code snippets. completely free and open source.
It exists, but it appears not to be used for anything
it is used for the input . . .
the PlayerInput component sends the input messages to the StarterAssetsInput component. the FirstPersonController component access the StarterAssetsInput component for the input
it's literally the _input variable on the FirstPersonController component
But this code has not a single reference that PlayerController accesses
wait
OMg
What happens if I generate another instance of this class?
Or there only can be one? (or it explodes)
wdym by generate another instance? none of these are singletons. you can have as many different instances of these objects as you'd like
Well last time I generated another istance of controllers they broke
Might have been my fault
But not sure
again, what do you mean by generated another instance
StarterAssetsInputs Inputs
Inputs = new();
surely you know how to read, right?
Link?
I mean
Okey gonna test if it explodes
Issue is not that its singleton
Or not
Issue is if there are multiple instances of this Component aparently
do you know what a singleton is? it's literally a type of object that forces only a single instance to ever exist. these components are not singletons therefore more than one can exist at any given time
Make sure that there are no compile errors and that the file name and class name match
you dont understand what I mean
of course how you use something also matters
i understand perfectly what you mean. you just haven't bothered actually explaining anything besides just saying "will this explode"
As mentioned I have mentioned to mention that when I created that class twice controlls broke
i know perfectly well that you are likely experiencing issues where all of the objects with these components on them are all reacting to the same input. of course that has nothing to do with having more than one of these components on it
the issue is obviously that they are all set up with the same input
for future reference, try fucking explaining what is happening instead of assuming everyone can read your mind and knows exactly what you mean when you say things explode with more than one of those components
Issue mostly comes with me not knowing terminology and thinking that I explained it in a wrong way.
the issue is that you didn't explain anything at all
Im pretty sure I did.
Anyway how does Unity Input system actually references this class?
it doesn't
the PlayerInput component sends messages to all of the components on the same object
but you can read the documentation pinned in #🖱️┃input-system if you want to learn how to use it
Getting this error
IndexOutOfRangeException: Index was outside the bounds of the array.
o
ShopStart 0 (at Assets/Scripts/Shop.cs:29)
Where it brings me to
void Start()
{
for(int i=0; i<=9; i++)
{
products[i].SetActive(false); //Error
}
Refresh();
}```
yo i want my player to be in a fighting state when he is punching so that every time he is punching a bool gets true for 5 sekonds and then turn to false
the way I learnt it used autogenerated class
how do i do that
Gonna look into guide
your array has fewer than 10 elements
show what you tried
📃 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.
https://learn.unity.com/project/using-the-input-system-in-unity?signup=trueЪ
Ehm... half of site is on my native language other half on english. How to fully make it eng?
Any idea on how I would fix? I am pretty new to this and am following a tutorial, although I seem to be getting more bugs than him haha.
found it
loop until you have reached the length of the array instead of an arbitrary number
and what about this did not work
Go through a C# course, not a Unity course
yes you lack the basics of working with array
the problem is that when i punch the first coroutin estarts but when i start punching when the first coroutine is still running the "isfighting" bool will be set to false fto fast
Either have 10 things in the array or don't try to get the first 10 things in the array
I did do a small C# course but I find it easier learning while doing than not doing.
u know what i mean?
👍
Assuming you are actually starting the coroutine somewhere, isFighting becomes false 5 seconds after starting the coroutine
doing isnt going to get you anywhere you if you don't know the basics available to you.
Instead of using magic number like 9.
Your looop would have the products[i].Length as limit
Thanks mate. Will give it a go.
ye but when i punch 1sec after the first coroutine starts, for example isfighting will be set to false not 5sec but 4sec after that and the second coroutine will be ignored
dont forget to check the link I've sent that descibes this process
#💻┃code-beginner message
Thanks mate.
show the full code
Are you intending to be able to start another coroutine while the old one is still running? I thought this was for a cooldown
Both coroutine start with your bool starting at true state, first one will be over in 5 second resulting in false state, if you started second coroutine withing 5 seconds of first one, ofcourse it will feel like second one has been completely ignored
Doesn't mean it has been
Well, it was a small course indeed if you're asking about array bounds now. Basics are important, go and make sure you understand them all more or less before trying to do anything meaningful in Unity, or you're gonna have a fair amount of similar issues along the way, which are not even Unity-related
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yea understood. Found it hard to focus on a full course though where I have learnt more making this game than anything else.
you don't check if isfighting is true anywhere
Why do you have two different cooldowns?
isAttacking and isFighting both seem to be cooldowns of some sort. Why do you have both?
isfighting is for something else
Use distinct names, or it will get confusing
ye
Box I looked up the API and other guide they have linked and the way they explained is the same as I got tought.
I havent found anything similar to what is done here?
guess that means you didn't pay too much attention to this
Where is the no autogenerated class
literally the first part
it's literally the first fucking part of that course you linked
i don't even see anywhere that they do use the autogenerated c# class for that
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}```
yes, that is literally not using the autogenerated c# class
public void OnMove(InputValue value)
{
MoveInput(value.Get<Vector2>());
}```
that is using the PlayerInput component. just like the StarterAssetsInput component does
WHAT is calling ONMOVE?//
the PlayerInput component
it does not call it directly, it sends the OnMove message to all components attached to the same object
So basically if I create Shoot inside the controll component I need to create OnShoot so it gets a call?
again read the docs
can u do 2 colliders in one object but they collide with diferent objects?
yes]

how
add 2nd collider component
So I was correct OnShoot
but i want that they collide different
then you need to explain what you mean
because that absolutely will allow two different colliders on the same object to collide with different objects. you just have to set up the layer overrides on the individual colliders
https://docs.unity3d.com/ScriptReference/Collider-excludeLayers.html
https://docs.unity3d.com/ScriptReference/Collider-includeLayers.html
You need to use these properties to override which layers the collider will interact with.
(they can be configured in the inspector)

What doesn't work?
Works now
is that error actually related to the code you showed?
im trying to make an active ragdol and need some help
im setting the target rotation of my ragdol to another model doing animations but its not copying the animation and im not sure what to change to fix it
Is there a way to get the current volume of an audio clip and turn it into a float? So like a head can bob around with its rotation dependant on the volume of an audio clip it plays.
You'd probably check the audio source.
It should be the object that contains the current status of what's being played. The clip would just be data.
Ok thanks
The audio source doc: https://docs.unity3d.com/ScriptReference/AudioSource.html
https://docs.unity3d.com/ScriptReference/AudioSource.GetSpectrumData.html you dont want the volume you want this data
Only way to expose variable to inspector is to serialize it or make it public?
Well yes
I just want to see sort of debug states
Debug states of what ?
Debug.Log exists
thanks
Not log
Just show variables without making lines of variables with serialize
"making lines"?
The variables need to be serialized in order to appear in the inspector
Doesn't look complicated at all.. 🤔
You're going to need to do something for each value you want to view, yes
It is annoying that there's no built-in "display" feature
Hopefully it isn't a wanting to type less issue.
does serialize works when you have multiple variables in line?
Like
bool a,b,c,d
the code below is producing the image above. why are the prefabs being made in this pattern? i want them randomly across the map but thats not what its doing at all
[SerializeField] private playerJoin players;
[SerializeField] private GameObject radio;
void Start()
{
for (int i = 0; i < 100; i++)
{
instanting(radio);
}
}
void instanting(GameObject instantObject)
{
transform.position = new Vector3(UnityEngine.Random.Range(-384, 384), 512, UnityEngine.Random.Range(-384, 384));
GameObject instance = Instantiate(instantObject, transform);
if (instantObject == radio)
{
instance.GetComponent<threeDimensionalAudio>().clint = players;
}
}

You can just switch your inspector mode to debug to see all the fields
You mean in VS studio?
In Unity.
it is a distinct curve
They're referring to the unity inspector
with randomness, anything can happen!
is it really consistent every time?
it seems so
its literally supposed to be random
its not even supposed to be a straight pattern
its supposed to be random points on a lateral grid
but they're the same every time?
but its creating a completely out-of-left-field pattern
i mean, look at the code
you mean like a...random pattern?
i see no reason it would do that
do what
make the pattern it does
how do you know when an animator finish animating it's state?
and this pattern is the same every time?
I'm assuming they're referring to this
they call start at the same point, then disperse in this pattern
this pattern
again
a second time
tf is happening
but what do i do to stop that
do i wait a second between each one
each instantitiate
x/y
its supposed to be x/z
in the code, y is fixed
yet, the y is changing in this pattern
so we're looking at x/z?
no we're looking at x/y
but you set y to be 512 always
correct
i am just as confused as you are
what's it look like from another angle? i remain unconvinced
I noticed that they're rotated. Do you've got any other code modifying the transform of these objects?
not to my knowledge
would you like a mp4
oh what are you even doing here
what am i doing here?
what object is this script on? because transform.position = will move that object, not position the object you spawned
ik
you should be spawning your object, then setting its position to your random value
but when you spawn a prefab it spawns at the object
i mean that would also work probably
ill try that rq
No it doesn't
it did from my experience
It spawns at the location you specify in the parameter
if you don't provide one, it uses the value of the prefab itself
Is there a way to tell when an animation is done? I've tried using normalizedTime and the length of the animation but I couldn't get it to work properly.
ahh, i should do that
since its max exclusive, would i need to do blockPrefabs.Length + 1 in order to have all the options in the array be possible?
The cleanest way is to add in an Animation Event which can call any function
https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
The reason it is max exclusive is specifically so that what you've done here will always generate a valid index
void instanting(GameObject instantObject)
{
var position = new Vector3(UnityEngine.Random.Range(-384, 384), 512, UnityEngine.Random.Range(-384, 384));
GameObject instance = Instantiate(instantObject, position, Quaternion.identity, transform);
if (instantObject == radio)
{
instance.GetComponent<threeDimensionalAudio>().clint = players;
}
}```
its max exclusive for ints
inclusive for floats
yeah i got it
i read the docs 🤓
oh wait, for blockPrefabs.Length it will start at 1, but arrays start at 0 so therefore its always a valid index, do i understand it correctly?
Yes, the length of a collection is always 1 higher than the highest valid index in the collection
length of a array is 1 higher then its max index, becuase random range is exclisive of max for ints, you can use it directly between 0 and length
3 elements in the array meaning Count = 3, and the element indexes are as follow: 0,1,2
can i make my terrain collider thicker
or, in general, can i make a mesh collider thicker
You shouldn't need to
is
public bool State {
get {
return state;
}
set {
state = newState;
}
}
preferred over
public bool GetState() {
return state;
}
public bool SetState(newState) {
state = newState;
}
or the otherway around?
colliders don't really have a 'thickness', they are a boundary line
Colliders don't have "thickness", they're always just triangles/quads
it's preference
if things go too fast, they go through the terrain
the top is just syntax sugar for the bottom
Semantics
Best:
public bool State {
get => GetState();
set => SetState(value);
}
Now you can do both
i know, im just wording it as simply as possible
I do like that
Change collision detection to continuous
i understand that colliders do not actually have Collider.Thickness();
You'll just need to make sure GetState and SetState modify a different variable, like a private _state variable. Otherwise you'll have a recursive loop
you could alternately shoot some rays out and manually correct for it
hmm... I see
to confirm, with continuous detection, i can go at any speed and never phase through?
or up the physics step which is pretty low in unity by default
"never" is a big ask. You can absolutely go faster than the physics system can even track
If your accessors do nothing else than getting/setting the backing field, you can use an auto-property instead.
public bool State { get; set; }
The two accessor methods are more the Java way of doing it.
ok lemme rephrase: if i reach terminal velocity will i phase through
actually i have no idea if unity had terminal velocity
Depends on what your terminal velocity is
Is there a downside to just doing
public bool state = false;
```?
does unity not have a maximum fall speed
but where do you pass the newState?
actually drag = 0
in the 1st option
so in terms of physics, that wouldn't make sense
Without having either functions or a property, you cannot directly assign to the variable in a UnityEvent. There's other minor differences but that's the most readily apparent
https://hatebin.com/nfzzgochqk
Somehow one momemnt inputs are null, next they arent null and like this on repeat. Whats going on?
it's the idea that counts, the execution comes after
Your life will be much easier of you watch this and have an actual understanding of how the physics engine works. It's probably not how you are imagining:
https://www.youtube.com/watch?v=NwPIoVW65pE
In this 2015 GDC talk, QWOP creator Bennett Foddy explains how to make your game feel solid without writing your own physics engine or breaking your entire game.
GDC talks cover a range of developmental topics including game design, programming, audio, visual arts, business management, production, online games, and much more. We post a fresh G...
Hmm.. I see
Kind of, if you ever want to modify what setting a new value does, with a property you change what's in the accessors, once. With a field you modify all 200 places it's being used
Prefer properties when exposing values outside of a class. It's C# standard.
My guess is you have two copies of this script and one of them has a null
yeah found it
yeah i just presumed it would use our physics
but i suppose coding that is more intensive than just getting pretty close
If we could code a physics engine that was 1:1 exactly like reality then we would no longer need physicists
even in scientific applications, they're just doing approximations (better ones, but still)
can someone explain why unity is changing the unitystream.unity3d to unitystream.unity3d.tmp?
'i just assumed unity had implemented reality for me'
if only 😭
is there a code question here?
exactly
i get it now
oh my bad, where should i ask?
idk what i was thinking about that
a better reason is that realistic gravity is not actually very fun in most games
id:browse to find a channel relevant to your question. and make sure to actually provide some details about wtf you are on about
and constraining yourself to it will make your life really hard
i mean true
also that would involve simulation every subatomic particle
and if unity can barely run a couple thousand navmesh agents, it sure as hell can't run enough subatomic partles for anything visible to the naked eye
The moment normal pc can run that optimization in code probably will go to second plan
Or compiler will do most of the job
what is "second plan"
hi i think I have an issue with this line, I dont see the sprite so could it be something to do with the camera's z position?
im unsure the technical terms on rendering
you're putting the sprite at the same Z position as the camera so it ends up being too close for the camera to render
https://unity.huh.how/screentoworldpoint
Amazing, you managed to output the word Clicked, yet completelyfailed to output the value of originalPos
thanks so much
still learning
ok turns out unity is much better at handling things then i thought
i can spawn thousands of rigidbodies at little to no impact on performance
im chilling turns out
when you debug output relevant information not just literals
thanks for the tip
you definitely should have some performance impact at thousands of rigidbodies. Anyways if you need thousands of objects like this, unity gameobjects is not what you want to use
well, its working for me
what do you suggest?
🤷♂️ i dont even know what you're trying to do. also "it works on my machine" is nice and all, until someone else runs it and gets confused how this game even got published when it runs at 2fps
Hello, is it possible to create a game object outside of classes and then reference them inside classes?
im just testing it
i have code intended to spawn 5 rigidbodies in random places but i felt the primal urge to turn 5 into 1000 and it surprisingly worked
what do you mean? and what are you trying to achieve?
creating a game object outside of classes makes little sense
I have a problem, when I have one button it works normally, but when I have more than one, they both stop working
Can someone tell me why?
Or how to fix this
should i make all GUIS UI objects?
Can't really tell with that little detail
Is one button covering the other?
well yea itll spawn and they can all sit there, sleeping. but try putting them all in the air near each other. They will absolutely destroy your performance when they all collide
I have a game object called "cat", and I want to reference it in multiple classes without doing "public GameObject catObject;" in each class
they all spawn in the air
and fall to the ground
I used a gameobject since I didn't know how to code a UI, but if it is better overall I will use that
The red button is the back button (back to main scene) and the "Upgrade1" for a upgrade @summer stump
Can you show the inspector for each button?
which one doesn't work
well some class is gonna have to reference it. Then other classes can reference that class who is holding the reference. Either way, you need a reference to something if you want to reference something
And if you delete either button, the other one works normally?
The scaling and size seem messed up perhaps?
No. Only the BackButton work
and all are colliding with each other? Use the profiler and see for yourself how the performance is. Also remember what i said above, it runs on your machine but if someone runs it and gets 2fps, they are refunding your game
should all menus be UI's
Are they an interface for the user?
But just if I deleate the Upgrade1 Button
yeah
Then they should probably be a user interface
they can be worldspace ui if you want 🤷♂️
Can you select the Upgrade1 button and show a screenshot of the scene view to show what highlights?
does that mean it would overlay a scene in the game
No
i should probably just learn how to use it
you can have it overlay the camera if you want
Do you get any errors in the console when you try to run the game with both buttons on it
they don't collide with eachother. they just hit the ground and roll
I was just thinking it might be harder to reference but it shouldn't be right
It will be exactly as easy or difficult to reference as anything else
perhaps easier, because UI usually exists before the scene starts
but not always
So i just found a bug. for whatever reason the simulator starts the game in pause mode when i have 2 buttons, when i press play i can press one of the two buttons but only once after that i get the error "Object reference not set to an instance of an object".
So look at the line the error is on. Something on that line is null but you're trying to use it anyway
i have a general question, as a beginner whos basically making multiplayer angry birds but with the barebones features, do you think a month and a half to complete it is do able
I wouldn't recommend doing multiplayer if you consider yourself in any way a beginner
would it be something I can just slap on at the end
using mirror networking
absolutely not
so what should I consider for multiplayer while im developing it
You shouldn't
I need to though
why
already written it up that itll be multiplayer
And how do I fix this now?
you haven't said what the error is yet
I did
password to join a room
Object reference not set to an instance of an object
So look at the line the error is on. Something on that line is null but you're trying to use it anyway
The absolute opposite
If you develop the game for singleplayer and decide to do mp, you'll be rewriting most of your code (basically starting over)
At least huge chunks of it
how would I get Destination over across these classes
Make it a member variable (instead of local one in your method), and reference the class
Or make a public method on the bottom class and pass it in
then you've overscoped your project and should back away before investing more time. the sunk cost here is that you've only written itll be multiplayer
Destination exists only inside of the OnStateEnter function.
Just a tiny detail to have in mind on the future, when I am checking for stuff like... is something within the range of X; the if should be a < or <=; does this have any significant impact in performance or it doesn't matter?
Do you want it to check less than or less than or equal to
Is not really relevant, the differnece is nimial, that's why I am asking, cause I have found this case several times, and I don't know if I should be doing a <= when a < would do almost exactly the same
The only question to ask is which one you want to happen
There is no better or worse
just use the one you want
Error CS8801 Cannot use local variable or local function 'Destination' declared in a top-level statement in this context.
sry, I'm a little confused
Ok
Maybe show what you've done
If it were me, I'd reference an instance of the other object and access a public member
I'm not gonna be able to help with errors without code. The variable needs to be inside the class though, of course
a variable in a class
It'd have the public accessor next to it
public Type Variable
so it'd be like
public GameObject catObject;
probably
theres no better feeling than fixing a bug youve been working on for 2 hours
getcomponent
If it's on the same object, or an object you collide with or something, sure
why is my asset fly up and falling down
Considering an asset is a file on a computer this is unlikely. Is your hard drive perhaps tied to several dozen helium balloons?
Do you mean an object in the scene?
perhaps ill have to see
Then either you've got code moving it up, your gravity is upside-down, or your camera is upside-down
well my gravity is 3
no sorry 4
my camera doesnt look upside down
and i touched any script in this project yet
Is either supernatural or this is the biggest upside in history
Show the inspector of the object
I'm lost on how to implement this
What is Destination and does it have a component named OnStateEnter on it
I THINK MY CAMERA FOR SOME REASON IS GOING UP
My best guess is this currently:
public Vector2 Destination = CatRoam.GetComponent<Vector2>();
I don't understand what fields I'm supposed to fill in with what
Vector2 is not a component
Vector2 is not a component
You would be getting CatRoam is FMState is a MonoBehaviour somewhere down the line
I think you should perhaps stop and go through the courses here though
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Question, is the trouble and time needed to learn how to make a simple two player multiplayer game not worth it? Should I resort to making my game pass and play despite it being a worse experience
considering a 6 week deadline
why a 6 week deadline
that is very short even for experieced people to make a good product
u probably wont have a multiplayer game done in 6 weeks
you are still learning
we started a few months ago, just recently we got to the development stage though
multiplayer is easier than fading ui as one element
use a canvas group..
what were you doing the first months if not development
id recommend fishnet
i use pro
why am i having dejavu?
not much time spent on the coursework, just some analysing and designing
you have been told about a few solutions, yes they require work to implement and have a few edge cases to work around but its all still very doable
brainstorming / outlining stage prob
How do you update navmesh via code?
whats that
do local multiplayer
The answer wont change from what we said above. Multiplayer is not easy. You cannot just add on the word "simple" in hopes it makes it easier. Making a 2 player game is the same as making a 3 player game, or a 4 player game. Even up to 10 players I would say has no difference
yeah thats the plan
Something that makes fading ui extremely easy
room based connection
local multiplayer is the middle ground between single player and multiplayer
ohh if its a connection its still technically full multiplayer
i mean 1 screen 2 players
nah i will give them what they want is more complicated then toss a canvas group on it, but not has hard as they make it out to be
yeah, but is it that difficult to just connect players using a simple method like using a password to join another player
Some people like to make ui harder than it is.
The solution to use a render texture is still not difficult. If done correctly the performance is fine
the solution with render textures taking up the entire size of screen negates performance by 2-3x, the other solution involves rewriting the whole ui system from what i was told
Again, #💻┃code-beginner message
You cannot just add the word "simple"
i feel ya, but for <insert problem>, too
you will have to learn networking concepts before you start
Guys, is there any way to do something like this? Is it about reducing the distance from where the bullet takes a collision with the forward of the crosshair? and also when it hits with that forward, the forward of the bullet will be the same as that of the crosshair. heres a cheap graphic
what exactly makes it difficult, if you can explain to someone whos never made one
how in depth
i know i want it to be a client-server connection
Yes, a tiny bit more
But either way, they are clearly just trolling
now try outlining the text, thick enough so that the outline of letters overlap, then do the same test.
it will be hosted on one player's compute
ya, i dont overlap my text..
and the other player will just connect to it
maybe its integral to the games design
to have outlines like that on the text
and you cant just “not do it” to avoid the issue
if it was then id still probably not do it.. i seen ur issue the other day.. try not using TextMeshPro/ overlapping text/ or maybe make a graphic out of the text and just fade the graphic instead
before you do UI in a game, learn what your UI framework is capable of and can do simply. Staring with a fancy idea that needs 100s of shims and extensions and complaints in a forum is a bad design.
and you seriously post a gif of yourself changing the canvasgroup alpha like i dont know how it works…
Why doesn't this work "NavMeshBuilder.BuildNavMesh();"? NavMeshBuilder doesn't seem to have a method called BuildNavMesh..?
I'm trying to rebuild the navmesh in a script.
if its intergral to the game design, it should not be a big deal doing the work rendering to texture, or messing with the stencil shader
the problem i guess is choosing a 3d engine trying to make a true-2D game
because unity uses meshes for everything
Everything. And in your 6 week deadline you said, you won't complete this in time. It isnt as simple as just connecting to another device and that's it, you need to think about if you want it to be client authoritative or server authoritative, both which have its difficulties. Common practices you see in beginner tutorials also no longer work (like making the player a singleton)
I have to ask out of interest, do you have an example of a "2D engine" doing this correctly in real-time?
godot and html5 canvas
i posts gifs for almost every component i mention.. some people generally dont know.. i don't know enuff about u to know whether you knew or not.. if u did just scroll past it?
alr ill take your word
How would I get a random Vector2 that is inside a collider?
but godot 4 cannot export to web with C# backend yet
It seems like they just have a render texture
at this point you are not evne here for a soultion just to complain
https://hamy.xyz/labs/unity-how-to-find-a-random-point-within-a-collider-mesh maybe this helps ya
I swear they solved it before too.. but this also isnt even a coding discussion
i know u can use bounds and stuff for more primitive colliders i think
Surprise surprise
you can just setup skia in unity and then write its buffer to a render texture
what’s skia?
what all browsers use to draw 2D
might be a bit low-level, and you have to DIY the whole interactivity bit on top of that yourself
i have an idea. a component you can attach to a ui gameobject. then it will calculate the bounding size of the object and all its children, create new canvas with camera render mode and camera rendering to a rendertexture of this calculated bounding box size. then it would replace the original element with a rawimage showing the rendertexture
could it be done?
i think there will be scaling issues
with mouse events but yeah
thats my current working idea
i just gotta make it
if theres something about unity you dont like you can always make stuff for it..
then you can turn around and make an asset from it.. and make some monah 💸
that was one of the suggested soultions
cha-ching
MMO starter template 🥹
i dont know about the cost of creating new separate camers and render textures for each set of elements i wanna do this for, but if the RTs arent full-screen maybe its cheaper
this might be a stupid question but if I get a nullreferenceexception error when it should have occured, is it a bad thing despite the rest of the code still working?
cameras in unity are pretty optimized tho, right
What's the code look like?
you can likly share rt's if a full screen one, if there is only 1 or 2 things at a time that need this feature at once
what would that change?
if its a null error from your code you need to fix it asap
How we'd evaluate your question and concern.
It would change us being able to answer or not...
a bit more variables up top
it'll tell us if the null error is a problem.. or if its a unity bug (that a restart) could solve
hmm not quite sure i understand that. each element would need its own canvas+camera no?
weapon instance gets spawned in by another code
What is the nullref on?
weaponinstance
show console error
anyways, the problem with scaling comes from moving the elements from the original canvas onto another one. it has to be at the exact same transform and the second canvas would need the exact same canvasscaler properties for it to work
Then yeah, seems like it's an issue you definitely want to address
It's null. Determine why.
im gonna work on a prototype
but the code works fine anyways
i know why it's null
but do I need to change it
Yes
as it is working as intended
a null error is bad
just that it is also intended that clicking the object when weaponinstance is null won't do anythinhg
it'll probably break ur code if thers any code running after the error
That is an unnassigned reference error
Unhandled errors will ruin your game
Not a null reference error
so EVERY error, even expected and supossedly harmless ones should be coded out?
if it could be unassigned then u should change ur code to react to that..
when it gets used.. check if its there first..
if its a error it is not expected
it is though
if(weaponInstance){//now run code that uses weaponInstance}
No such thing as a harmless error
Then you should handle it so it is not an error
Exceptions, as their name suggest, are exceptional. They should not happen during normal operation.
If one occurs, no code after it will be executed on the method for that frame
they are called exceptions for a reason
yup, ez fix.. change ur code around a bit to account for that possibilty
ohh, so only that frame of the game would be ruined?
I will fix it though thanks
No
At LEAST that frame will be ruined
lol, very minimum
i see
If you see an error, stop everything you are doing and resolve it
if something is aloud to be null and you dont want to use said thing if its null just null check it with a if statement
if its not to supposed to be null fix it
obj.transform.position = Vector3.one; // let's say this throws an exception
Debug.Log("sample"); // this will NOT be executed
^ so depending on when the error happens it can be minor.. or can ruin the entire script
Or other things on the stack that's being resolved as well
the final goal is to have ur console appear like this 🙂
Debugs get removed from normal builds right?
but lets say it would normally run like that but sometimes have an unassigned reference exception
u need code to deal with it if it is
if(weaponInstance)
{
//now run code that uses weaponInstance
}```
anytime theres a possibility it may be null.. and you're aware of that.. you need to make sure no code runs while its null
or no code runs that tries to use the reference that is null
Then write code the handle that edge case
this the same as if(weaponInstance != null)
i always heard of that, an edge case is an error which sometimes occurs or what?
like how raycasts are normally wrapped in an if statement.. if the raycast doesn't hit anything u dont want the code to try to do anything with the hit (which wouldn't exist)
the error is gone nwo
edge-case <-- a case that may happen.. even if it is rare
like an unlikely use-case
oh thanks for the tip, i wrote the null one
I think you're better off writing a custom ui shader or using rendering features(urp). It's gonna gonna be more performant than what I think you have in mind.
im 100% in agreement with this statement ☝️
Edge case is a possibility you didn't account for.
Example, you open a file to write to it, but didn't account for the possibility that the file is already in use by another program, throwing an exeption when you try to open a handle to it
Render Features are 🔥
@queen adder Though not ui, this sort of achieves the effect you want with render features using the stencil buffer:
https://www.fraculation.com/blog/overlapping-mesh-render
thanks, im sorry for getting upset earlier. i just have no idea where to start with attempting that
from the title this looks like exactly what i need
Check the link above. It might give you a quick start and the ide of what you need to learn to achieve the effect.
I was wondering, my character can snap to a surface on input, as if it could stick to it, and I'm searching if it's possible to rotate also the Cinemachine camera orbits, as if the referencial was changing. Is there a way to achieve this ? Maybe it could be useful to have a way to edit the camera global axis ?
i'd like to believe theres a setting in the component you can use to offset the camera like that
"dutch angle"
im not gonna get lying tho.. dont know nuff about it
Pretty sure cinemachine has a "world up transform" thatll allow you to do this
oh ya that too, forgot about that tickbox
None of them seems working
Do I need to add some code maybe
Im on mobile so cant exactly show it, but I remember there being a field directly for the "world up transform". And you assign a transform in there
Okay thanks gonna search dat
Destroying assets is not permitted to avoid data loss.
If you really want to remove an asset use DestroyImmediate (theObject, true);
UnityEngine.Object:Destroy (UnityEngine.Object)
Why am I not allowed to use Destroy?
Did you read the message you pasted? you are trying to destroy an asset
I want to
Then read the message again and you'll learn how to
Destroying assets is not permitted to avoid data loss.
But I've used Destroy a lot and that never happened :o
Because you are now trying to destroy an asset, a file in your project
not a game object in a scene
You probably never destroyed an asset
private void DestroySelf()
{
foreach (var drop in _drops)
{
if (!Chance.Of(drop.Chance)) continue;
var amount = Random.Range(drop.MinAmount, drop.MaxAmount);
Enumerable
.Range(0, amount)
.ToList()
.ForEach(_ => ItemDropService.Instance.DropFrom(
transform.position,
PlayerMovement.Instance.GetFacingDirection(),
drop.Item)
);
}
if (!_destroyOnDeath) return;
UnregisterSelf();
Destroy(gameObject);
}
That last line is the one
I thought that just destroys the object that has the script
Can you show the inspector for that object?
Just read through it and the idea seems right, its definitely what i want. But this seems to be for regular game objects, not UI, so Im struggling to see how to apply it to my issue
Do you have a variable called gameObject?
It does. If the object that has the script is an asset (for example, a prefab), then you cannot destroy it
What calls DestroySelf
And i understand the concept of the stencil buffer, i just dont know how to set it up globally on my ui
public void Damage(int byAmount)
{
_hp -= byAmount;
if (_hp <= 0) DestroySelf();
}
So how do I destroy the object, not the prefab
Okay what calls Damage
A tool Scriptable Object
if (_dealDamageToTiles)
{
var exists = TilePlacementService.Instance.PlaceableExistsAtPosition(roundedMousePosition);
if (!exists) return;
var tile = TilePlacementService.Instance.GetPlaceableAtPosition(roundedMousePosition);
tile.Damage(_dealtObjectDamage); // <--- here
ConsumeDurability(1);
}
Basically whenever the player left clicks a tile
Goodnight. I have a problem and I don't know how to solve it. When I click play to move to the next screen, it says there is no camera. Does anyone know how to solve it?
So tile is probably a prefab
It is
Can't destroy a prefab
I don’t need anything spoonfed but how would you begin to go about creating an effect like this
I don't want to, I want to destroy it as if it were a normal object
Is there a camera on that next screen?
Which object do you want to destroy
Also, because this doesnt deal with actual shader code and just changes URP renderer data inspector settings, it isnt much helpful..:/
Cache the click point on mouse down, calculate the distance and direction until mouse up
There is a prefab that has a DestroyableObject script on it.
That script has the Destroy method. Which lead to the bug
Show a screenshot of your hierarchy when you're on the screen that says there's no cameras
So what object do you actually want to destroy
I can do that bit but I mean the effect
isn’t the unity ui system render pipeline-agnostic?
What effect?
The copy of the prefab
*instance of the prefab
Yeah, I'm not sure if that exact way would work with ui. Did you give it a try?
That's why I mentioned a custom shader with a stencil buffer, basically what this urp setup does for you.
helpful
It would show a stretching triangular sort of shape (as seen in the photo) which originates at the slingshot ammo
which one
It is an important difference. No need for the snark
I was going to just make a normal slingshot but I’m having issues with the projectile motion if the weapon is pulled back
Alter the vertex of a mesh based on the place the mouse is while held down
Thanks 🙏
Wait. Is it 2d or 3d?
2d
So at runtime I spawn a bunch of these that all have the DestroyableObject prefab. And that DestroySelf method should destroy the spawned rock, not the prefab
@polar acorn
I am not great with 2d, but I think you could stretch a sprite renderer
So you would want to call that method on one of those objects, not the prefab
So, I don't see a camera in the Menu scene, meaning before Jogo loads it would be showing that error. Is that first screenshot before or after starting the game and attempting to change scenes?
Instantiate(randomPrefab.gameObject, transform).transform.position = targetPosition;
Is the instantion wrong? Because that's exactly what I intend to do
Cache the result of instantiate
The destroy the cached object
Where are you storing the result of Instantiate
I don't
So then how do you intend to reference the object created by Instantiate
first screenshot after starting
my game always worked normally, not what changed
So, if that's what the hierarchy looks like while the message is displayed, that would be the problem. There's no camera in that scene, at least none that I can tell at a glance is a camera
Ohhh I think I get it
Thank you
If I add another camera, the error does not appear, and the screen does not change, it remains in the main menu
can some explain what bool jump = false; mean compared to bool jump = true;
I cannot play an animation clip on command without an animationController right? There is no such thing as a .play for the animation component isn't it?