#💻┃code-beginner
1 messages · Page 633 of 1
Make a vector that is your horizontal movement.
Make another vector that is your vertical movement.
Add them both together to make your final movement vector.
Pass that value, multiplied by deltaTime, to controller.Move
One of two things is happening then:
A) Something else is setting the values back to white
B) The objects you're looking at in the inspector and the ones getting logged are not the same object.
Are you maybe changing the color of a prefab rather than the ones in the scene?
your losing me
that function changes the color of the icon(button) but wont for the child
- Make a vector that is your horizontal movement multiplied by speed
- Make a vector that is your vertical movement
- Make a vector that is (1) + (2)
- Call
controller.Movewith (3) times deltaTime
So is the text you're trying to change the color of the one in the scene, or is it on a prefab?
Easy way to test, put this line at the end of the coloring section:
Destroy(windowText.gameObject)
If the text still exists, then you're recoloring the wrong object
im still lost but is this what you wanted?
In this case, since it is a 3D project "Horizontal" meaning XZ, and "Vertical" meaning Y
awesome i changed the text name then debug it it is indeed the wrong child
thanks
what??
"Vertical" = W + S
"Horizontal" = A + D
im so confused
Horizontal movement: On the ground
Vertical movement: Up and down
You know
like what you were already doing
Just all in one line so your math was a train wreck
I am talking about basic addition
no not that
You have your horizontal movement (in two dimensions because you're on a plane) that is controlled by your horizontal and vertical inputs. You want this value, multiplied by speed.
You have your vertical movement, which is gravity and jumping. You do not want this multiplied by speed
So make two variables
what
Here, you're doing horizontal and vertical in the same line. Then multiplying it all by speed and deltaTime
Z = Vertical
X = Horizontal
Z and X = Horizontal
Y = Vertical
I'm not talking about inputs
I'm talking about world space movement
I've explained exactly what I mean by "Horizontal" like ten different ways
Please read them
Feel free to scroll up I'm not elaborating again
Get your sidey-widey movement in one vector.
Get your jumpy-fally movement in another vector.
Add them
is that better?
oh my god you dont have to be an asshole about it
i thought you were talking about inputs not world space
I explained exactly what I meant several times
Hello, I currently have the following
if(Physics.Raycast(ray.transform.position,ray.transform.forward, out hit,Mathf.Infinity,layerMask)){
hit.collider.gameObject.Face=1;
}
Face is defined in a script of the prefab numFace with a getter/setter
I can guarantee that the raycast will always hit a numFace object, how can I cast the collided gameObject to numFace so Face can be set
GetComponent
you dont cast, Face is not a GameObject. it's (hopefully) a monobehaviour, so you would GetComponent<Face>
and setting it equal to 1 would also make no sense
You can't cast GameObject to a component, components are not extensions of GameObject, just a type of class that goes on them
still no need to be an asshole
And no need for you to just ignore everything I was saying to answer your questions
ah, ty! I'm so used to standard OOP, i thought monos just like. assimilated into the object or smth. ty for clearing that up
fym ignore i was reading it i just thought you meant something else by vertical and horizontal what??
this is still OOP, gameobjects just have a list of components. its composition
Basically, GameObject has a component. A cast would imply a GameObject is a component. In this case, no avoiding the GetComponent call, even if you're certain it's only the one kind of object that'll get hit, you'll need that extra step.
GetComponent calls should be avoided when possible, but situations like this fall into the "not possible" category
this sounds like exactly what i had before that wasn't working
- Make a vector that is your horizontal movement multiplied by speed
- Make a vector that is your vertical movement
- Make a vector that is (1) + (2)
- Call
controller.Movewith (3) times deltaTime
You're missing steps 3 and 4. this results in Time.deltaTime only multiplying with the vertical movement
You'll want to actually store the result of (1) plus (2), so you can multiply that result by deltaTime
Vector3 is a struct, it doesn't produce any more garbage making a variable of type Vector3 than it does doing the math all in place, so you don't need to cram it all into one line
like this?
Yes, that should fix your issues with the horizontal being too high (now it's getting scaled by deltaTime). You might also need to modify whatever value you have for y since it's smaller than it was before
you should also do the speed multiplication separately so that you can normalize horizontal before multiplying by speed (or at least clamp its magnitude) so you diagonal movement isn't faster than other horizontal movement
speed is still effecting my y value for some reason
hello all, does anyone know why my reload code isnt working? it keeps on firing even when its supposedly reloading
void Update()
{
if (target != null)
{
// Calculate the predicted target position accounting for gravity.
CalculatePredictedTargetPosition();
// Rotate turret to aim at the predicted position.
CalculateRotationToAimPosition();
// Fire if turret is aimed and not reloading.
if (!isReloading && Time.time >= nextFireTime && IsAimedAtTarget())
{
if (shellsFiredInCurrentMag >= magSize)
{
StartCoroutine(Reload());
}
else
{
Fire();
shellsFiredInCurrentMag++;
nextFireTime = Time.time + fireRate + UnityEngine.Random.Range(-0.1f, 0.5f);
}
}
// If target is out of range, clear it.
if (Vector3.Distance(transform.position, target.position) > maxRange)
{
target = null;
}
}
}
IEnumerator Reload()
{
isReloading = true;
yield return new WaitForSeconds(reloadTime);
shellsFiredInCurrentMag = 0;
currentFuzeTime = timeOfFlight + UnityEngine.Random.Range(0.25f, 0);
nextFireTime = Time.time + fireRate;
isReloading = false;
}
What does the current form of the code look like
And where do you assign y
before update
Show where you set it
well yeah but then it changes later
also just mentioning that when you do wanna do GetComponent calls a nice safe clean way is to use the TryGetComponent function where instead of
MyMonoBehaviour inst = gameObject.GetComponent<MyMonoBehaviour>();
if (inst != null)
//thing with inst
you can just do
if (gameObject.TryGetComponent(out MyMonoBehaviour inst))
//thing with inst
So, you change y after you do the movement?
https://paste.mod.gg/lxsopejqwxdh/0 so now the text will change but the icon color wont seems to have gone in reverse and the debug says its changed
A tool for sharing your source code with the world!
i ran it through ai just incase but that cant work it out
Should I
A) Have one script that a bunch of different objects refer to, to change X object in the UI
B) have every script reference the part of the UI they need to change themselves?
yuh
Have you used events / UnityEvents before?
If this is everywhere that y is modified, it is not affected by speed
well when i sprint it changes how fast i fall
should i like restart my unity or smth cause
What does "sprinting" entail
at this point you should share the entire class using a bin site so digi doesn't need to keep asking for more and more code as it is revealed that you are doing more and more that could be affecting your issue 👇 !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/, https://scriptbin.xyz/
📃 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.
Yes but nothing on my UI is necessarily ever going to be changed by more than one script so is it still worth it to still use it despite that?
i mean that's up to you but ideally imo UI stuff is the perfect use-case of events because in most cases your core logic shouldn't need to acknowledge any of the UI stuff exists
i restarted my u nity and it worked
what
your core logic stuff would just fire off relevant events when stuff changes and your UI Manager would listen and update based on those events
You probably didn't recompile after changing the file. It is usually automatic
But if it got stuck, it wouldn't recompile
Ok thanks.
small example from a project to show what i mean but you probably get it
UIManager.cs
private void Awake()
{
GameManager.OnActiveTurnMovementChanged.AddListener(RefreshMovementUI);
GameManager.OnNewTurn.AddListener(RefreshTurnCount);
}
private void RefreshTurnCount()
{
turnCountText.SetText("TURN - #" + GameManager.Instance.TurnCount);
}
private void RefreshMovementUI(GameInput newInput)
{
string text = "[" + newInput.ToString() + "]";
if (newInput != GameInput.NONE)
text = text.Colorize(Color.yellow);
selectedInputText.SetText(text);
}
what happens after i installed .NET SDK?
Also this kinda depends on your use case. If you're talking about updating a health bar, only one script would be updating this UI health bar of course, but many other things might be interested in the health. In that case youd already probably have events setup.
In the case of pressing tab and opening up a menu, that would make sense if you wanna just do it directly
you need to restart your computer. then you have the .net sdk installed
also how are you still on this? it's been an entire day
oh i went to sleep cuz it took too long to download
yes, now you can open up the other file you had and find all of the usages of that event you were having trouble with
you likely changed something that you don't remember
i just didnt save the work i did last night
right so you changed something, you forgot what it was that you changed, and now you've finally saved and compiled your code so that it updated in unity
no i remembered i didnt save what i did last night
i did something last night that caused the issue so i just exited without saving and now its fixed
if what you had done that caused the issue wasn't saved, then the issue would not have appeared because that change would not have been compiled.
i feel like this is a really bad/inefficent way to detect the key being pressed and then detecting when it is released, but i couldnt find a way to do it with the input event systems. any suggestions?
I wouldnt GetComponent like that and instead store the array/list by the type
Getting inputs in FixedUpdate is a bad idea, there's a chance that when the user presses the key, that FixedUpdate won't actually call at that exact moment
oh thats a good idea
yeah that is what im thinking. My original plan was a input event that would detect when being pressed (works) and then sets it to false when stopped
but i couldnt figure out how to pass a bool through the event
That's only really for GetKeyDown or Up since those are for one frame.
Using fixed update here just makes no sense cause nothing physics related is happening here
You could use GetKeyDown and Up,which are only true for one frame
Which would have to be in update also
Oh is that so? I assumed it was the case for all input methods
Makes sense though!
so like
update{
if(getKeyDown.S){do stuff}
else if (getKeyUp.S{do other stuff}
}?
In my game, I do input in update to store a throttle/steer float, which then gets used in FixedUpdate to drive my vehicle
I mean it still kinda applies to GetKey but it's way more rare youd have an issue. Youd have to hold a key down for like 1 frame which isnt feasible without a tool like AHK
Yea pretty much
Excluding the obvious syntax errors
It keeps a nice separation between what the player is doing and what the actual vehicle does
ty for the help
One more thing. For the else statement, you could consider a flag to prevent each frame from iterating and setting everything to false, but this could be considered a micro-optimization if we're talking about a handful of iterations
if(Input.GetKey(KeyCode.S))
else if(!platformsAreFalse)```
I guess similarly for each frame for when you hold down the input assuming those platforms are only ever set true/false in these scripts. One benefit of the event driven input system is that you can just listen for the toggles.
How would I make a boxing camera that works like Fight Night Champion's? I'm trying to make a boxing game and that's the thing that's holding it back from being presentable
After careful consideration and watching this talk https://youtu.be/raQ3iHhE_Kk?si=a53ftMwIXI5-_uG_ I will be learning how to use ScriptableObjects.
Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...
Good call . . .
My logic now works the way i want it to but is there any drawbacks to why I shouldn't use a IEnumerator Coroutine inside of another IEnumerator Coroutine?
There aren't really any drawbacks, aside from maybe making the code less readable and more bug prone.
Depending on how you have it implemented
where should i ask questions about like scene vs play issues with lighting(?) maybe transparency?
more or less I have it to keep track of a removed object that needs to be brought back during a while loop for tracking a durability counter. (Imagine Minecraft block break but the block comes back after X seconds)
This is more about the purpose of the implementation, rather than implementation itself
Coroutine sequencing is hard. Sometimes I do feel like I nest too much
#archived-lighting #archived-urp #archived-hdrp #archived-shaders
If not sure which one, maybe start with providing some info in #💻┃unity-talk
ty
Sometimes I feel like update would be better off as a coroutine by default ;p
I for sure was confused when i put a while loop in update and my project broke XD
Can't imagine how that would work 🤔
Just being able to yield the update execution would be nice instead of creating the coroutine in start
not a big deal, but I don't see any disadvantages to giving more control of how you exit the update
You can return from update if you need to exit it earlier.
Yeah but for example you've some transitional controller where you're fading from one scene to another. You'll usually have the pause the execution of everything until it's complete, especially your primary event controller.
So I'll end up having this sequence of logic deeply nested on top of a single coroutine
That's the way. State machines could help. Engines usually try to keep their default implementation as simple as possible. If every update on a MonoBehaviour was a coroutine, it would add a lot of overhead that is not even required in most cases.
Also by design an Update function/method is intended to be something that updates the object once per frame, ideally fast-fast. Making it a coroutine would basically break that assumption entirely.
Good evening, I am trying to make the water tiles in the game speed up when the player touches them but they don't seem to be interacting with each other. I can make the player delete when the edges are touched but the water does not do a thing. When the player object speeds up thats me clicking the mouse. I added the composite collider 2d and the waterBoost script to it but nothing. What am I doing wrong? x_x
Trying to reload a basic scene, how come the existing hierarchy components such as UI get deleted? The only thing that stays is the GameManager, which contains in its script DontDestroyOnLoad(), and I was trying to understand how scene transitioning works. Basically I have an int in my GameManager script that I wanted to see if I reload the scene, it would keep the number, but then everything gets deleted so the GameManager cant reference the UI text GO anymore
Playercontroller script and waterboost script
Scene reload means that the current scene is unloaded entirely(aside from ddol objects), then the target scene is loaded.
ye my blind ass just noticed that the hierarchy after the reload gets a "Game" GO drop down that contains everything else. But then the GameManager loses the textmeshpro ref i dragged in its inspector. Im guessing im gonna have to dynamically assign these via script then ?
Yes.
The game manager shouldn't hold and hard references to the scene objects that would be unloaded. It would make sense to have some non ddol managers that hold reference to objects in the scene. And the game manager can access them(for example via singletons or by having them register with the game manager).
I just rewrote almost everything in my game to use scriptable objects for certain things and it's taken me all night so I hope it was worth it. 😭
why does unity hate it whenever i do anything with prefabs? i have to reload the project or itll just keep running the unity_self error whenever i make a new prefab(most the time)
That's great! They have their uses; they save on performance (memory) and are key for default data where multiple instances share the same . . .
!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/, https://scriptbin.xyz/
📃 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://paste.ofcode.org/349HZK4P2Mjf8nU4TXuxZhh
I need help creating a EnemySpawner but this spawner is following the player with two points (minSpawn) (maxSpawn) that show the area around the player and it make a flat plane. But the issue I having right now is trying to figure out how to make that while also making sure they don't spawn to close to the player. So no matter where the player move it will spawn in this area
Can make your life easier by just using a radius
is there a way i can find where this error is sourced to? it only happens sometimes, but happens immediately after running (the inconsistency is making it hard to find a source)
Are you using any custom plugins
or making any editor tools
Try just giving Unity a reset, otherwise it's probably something related
uhh smooth pixel pixel is the only outside plugin
wdym editor tools?
ill give it a reset
Wasn't sure how that would work either
the distance of an enemy to spawn would simply be the minRadius
well, between the min and max radius
But how would I make it inbetween?
Could you give me a expample please?
https://discussions.unity.com/t/random-point-within-circle-with-min-max-radius/724904/7
There's also a method Random.insideUnitCircle
how many dumb questions are allowed in a day? I'm struggling to figure out a way to pass variables from an object to a main controller for all objects of that type. I don't know if i should do inheritance or polymorphism.
ex. Object Controller does thing based off of if it's interacting with Object1, Object2 or Object3.
Could you provide a bit more context? sounds abit more inheritence pilled but the passing of variables might need more elaboration
!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/, https://scriptbin.xyz/
📃 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://paste.ofcode.org/69RsHhy5Pw7YwK9TJbd9rQ Here is the controller script. What i want is to have the different trees have different treeDurability and treeRespawn based on which tree I am interacting with.
ah for this you would probably just have like a TreeBehaviour MonoBehaviour script that has those values
and have different prefabs for the different types
following a flappy bird tut, but my "pipes" spawn too frequently or close together
is this a scaling issue? considering i stretched the image in unity to be more pipe-like... hlp..
A lot of this logic looks like it should be on the tree itself
I have tried that but when the tree is not active the script stops and doesn't active it again (unless i'm doing something wrong.)
Have you tried changing the "spawn rate" value in the pipe spawner?
oh lol wait
That would be because you are disabling the whole object, coroutines wont run. You could just disable the visualizes and collider if you want, or run the coroutine on another object that doesnt get disabled
ty 😭 🙏 this is gonna be a long journey
How to Design a Flexible Skill System Like League of Legends or Turn-Based Gacha Games Without Thousands of Classes?
I do appreciate your input. I'm just trying to decide what is best for the project as a whole. i know this is a simple one just for practicing some theories, but i also want to think about it if I did scale it up. I'm still very new to coding and making different scripts and objects not just work together but also efficiently.
scaling it up isnt really an issue here, but i get what you mean. there is just not that many solutions here without adding more complexity. I think the simplest solution would be disabling visuals and the collider. Another thing you could do is have some sort of respawn manager in each scene as its own object. instead of an object trying to reenable itself, you could tell the respawn manager "activate me in 5 seconds".
dont have thousands of skills then if you dont want thousands of classes. its pretty likely your skills will require unique functionality, there isnt a way around having to declare what that functionality is if you want it in your game
So after messing around a bit I figured it out! 😄 Just needed a main tree class that the controller referenced and then each type of tree child class just input their variable into that main tree class.
oh mightve misunderstood what you were talking about in my deleted msg
well glad it works 👍
hi, i´m trying since 1 hour+ to find how to add/activate/diasctivate force on collision with a specific object only with visual scripting, could someone help me?
We don't really do visual scripting here, these channels are for C#. See #763499475641172029 or learn C# from the pins of this channel
i fixed it lol
why is it impulse tho
instead of force in the rigidbody 2d add force
Impulse is used for one-shot forces, Force is used for continuous forces that are applied every physics frame
For example impulse = jump, force = walking
that´s what i actually wanted to do that it becomes faster and faster but it didn´t work
If adding force continuously doesn't accelerate you infinitely, you have drag (linear damping) or friction slowing it down
force is in mass * acceleration (aka mass * velocity / time)
impulse, aka momentum, is in mass * velocity
thanks, i will see : )
How do i add a file picker that works for Web gl and windows, i saw this https://github.com/Netherlands3D/FileBrowser but it says Requires .NET 2.0 api compatibility leve and im not sure if unity 6 has that?
Yeah that's not an issue
okay great
so the .net is backwards compatible ro do i somehow have to downgrade it?
.net isn't backwards compatible afaik, but unity has been using 2.1 for a while so there shouldn't be any problems
okay
Best thing is to try it out
Hi guys. So my character has the same problem as yesterday. It shows he doesn't have ground Check but he can still jump. what should i do?
!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/, https://scriptbin.xyz/
📃 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.
Not sure if that vscode is configured either
so what should i do?
and i dont really think it has to do with the code because i had the same code as yesterday and it worked just fine
- configure your ide according to #💻┃code-beginner message
- share your code properly according to #💻┃code-beginner message
and yeah, it's not really code related. read the errors you're getting lol
it's practically screaming the issue
don't post chat gpt code
!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/, https://scriptbin.xyz/
📃 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.
public class PortalWarpToArena : MonoBehaviour
{
public Transform arenaSpawnLocation;
private void OnTriggerEnter(Collider other) {
print ("something is touching the portal");
if (other.CompareTag("Player")) //Ensure player has touched portal
{
print("Player is touching the portal");
TeleportPlayer(other.transform); //Teleport player to destination
}
}
private void TeleportPlayer(Transform other) {
//print("Moving player to destination");
other.position = arenaSpawnLocation.position; //Move player to destination
}
}
}
I've put the destination game object in the right spot in the editor, am I missing something stupid that's stopping this from working?
the console is showing both print statements properly, it's definitely seeing the player touch the portal object
Does the player use the character controller?
Yeah I'm using Unity's starter third person character controller
If that's the standard character controller then you have to disable it before teleporting the player and re-enable after because the CC tracks its own position separately
Interesting, so the character controller is already controlling the player location and is overriding the portal, if I understand you correctly?
right
not exactly "override", more like "conflict"
it can lead to unexpected behavior, not just "no effect" if it were overriding
Okay cool, so can I just put in public gameobject for it and reference it, then disable>move player>enable?
I'm not at the computer now, walking the dog, didn't expect an answer so quick haha
public CharacterController
Not GameObject
Gotcha, thank you
You can also call Physics.SyncTransforms() after doing the teleport instead of enabling/disabling the CC, but that'll recompute every rigidbody and CC in the scene and depending on how many you have and how often you teleport it, you might still want to do the enable/disable thing
if u use PhysicalVelocity
I should do it
physicsVelocity.Linear = moveData.speed * direction*deltaTime;
or
physicsVelocity.Linear = moveData.speed
you don't multiply deltaTime into your velocity, no
that happens automatically inside the physics simulation when it decides how much to move the object each frame
Wait is the same true from AddForce?
correct, never use deltaTime in AddForce
Yes, if used in FixedUpdate, don't use deltaTime with AddForce . . .
It’s in update…should I be using it in fixed update?
Yes, remove it from Update . . .
It's a physics method; it should be applied in the physics update, which is FixedUpdate . . .
Alr
Now it's just giving me
Assets\Scripts\Gameplay\PortalWarpToArena.cs(9,16): error CS0118: 'CharacterController' is a namespace but is used like a type
using UnityEngine;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
namespace Unity.Template.CompetitiveActionMultiplayer
{
public class PortalWarpToArena : MonoBehaviour
{
public Transform arenaSpawnLocation;
private CharacterController characterController;
private void OnTriggerEnter(Collider other) {
print ("something is touching the portal");
if (other.CompareTag("Player")) //Ensure player has touched portal
{
print("Player is touching the portal");
TeleportPlayer(other.transform); //Teleport player to destination
}
}
private void TeleportPlayer(Transform other) {
//print("Moving player to destination");
characterController.enabled = false;
other.position = arenaSpawnLocation.position; //Move player to destination
characterController.enabled = true;
}
}
}
I assumed I'd need to use GetComponent to grab it but it won't even let me past creating the variable
Do you have a type — in this case, a class — called CharacterController?
did you make a CharacterController namespace somewhere in your code or is there one somewhere inn this Unity Template code?
Why is your code in this Unity.Template.CompetitiveActionMultiplayer namespace?
¯_(ツ)_/¯
I imported the multiplayer stuff to play with it and even after removing it because it wouldn't let me start in my own scene it left its stink all over my project. I guess I have to start over
I have this
Creating a new project and copying my scene and scripts seems to have worked, the player is teleported when touching the portal surface. However, now the camera isn't following the player.
oh the joys of learning
Okay I just deleted that unit.template.competitiveactionmultiplayer shit after recreating the entire project and it works now. Thanks for your help.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ClickToBig : MonoBehaviour, IPointerClickHandler
{
[SerializeField] private Vector3 _bigScale = new Vector3(20f, 20f, 20f);
[SerializeField] private Vector3 _smallScale = new Vector3(5f, 5f, 5f);
[SerializeField] private bool _isBig = false;
private RectTransform rectTransform;
public Button closeButton;
For some reason I can't drag/drop the close button in the field and clicking the search icon yields no results.
You can't drag a scene reference into default references
It needs to be a prefab
What are you trying to do?
^ This.
In general assets (things in the project window) cannot reference things in scenes (things in the hierarchy window)
Yeah, I saw online that the script needed to be added to the button, but I have to adjust script because the button in-game is doing things that the other object is doing. I think I might know how to fix though.
I never insert anything into those default reference windows if that means anything to you :p
Ok, so I correctly assigned things and now my intentions are being met. I have an object (Let's call it A) that, when clicked on, it grows big AND a Dialogue box appears that contains a Close Button. When the Close Button is clicked, the box is destroyed and Object A shrinks back down to original size. This is all good.
The issue is that the Close Button itself is also growing when object A grows. I thought the Listener method was supposed to make it so the Button wouldn't do what Object A does, but 'listen' to what it is doing so the button knows what to do when to do it.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ClickToBig : MonoBehaviour, IPointerClickHandler
{
[SerializeField] private Vector3 _bigScale = new Vector3(20f, 20f, 20f);
[SerializeField] private Vector3 _smallScale = new Vector3(5f, 5f, 5f);
[SerializeField] private bool _isBig = false;
private RectTransform rectTransform;
[SerializeField] private Button closeButton;
private void Start()
{
if (closeButton != null)
{
closeButton.onClick.AddListener(ShrinkObject);
}
}
private void Update()
{
rectTransform = GetComponent<RectTransform>();
rectTransform.SetAsLastSibling();
}
public bool IsBig
{
get => _isBig;
set
{
_isBig = value;
if (_isBig)
{
transform.localScale = _bigScale;
}
else
{
transform.localScale = _smallScale;
}
}
}
public void OnPointerClick(PointerEventData eventData)
{
if (_isBig)
{
return;
}
IsBig = !_isBig;
}
private void ShrinkObject()
{
if (_isBig)
{
IsBig = false;
}
}
private void OnValidate()
{
IsBig = _isBig;
}
private void OnDestroy()
{
if (closeButton != null)
{
closeButton.onClick.RemoveListener(ShrinkObject);
}
}
}
Is this a bug in unity? I can't even get near of my object without seeing it disappearing
select it and press F. Your camera near/far clip is set to something else
btw not code related #💻┃unity-talk
mb i just didn't know in which channel is should post it
kk man thx i'll try this right away
is close button child of the thing that expands ?
whats the purpose of the rectTransform thing in update?
btw you can just do rectTransform = (RectTransform) transform
no need for GetComponent
Your code is doing transform.localScale = _bigScale; That means whatever object this script is attached to is going to be scaled.
Object A and Button are not children of each other
So if the script is on the button, it's the button that will scale
^
if transform is the button then it will expand
I get that, but how will I assign the button/script relation so that Object A shrink when button pressed? My original reference was when I tried to attached object to the script itself (which we covered you can't do). Currently it is attached to the field of script that is on Object A.
the script is not in the scene?
why can't you do[SerializeField] private Transform objectA
Well the script is assigned to Object A. I set up the script a bit ago to grow/shrink Object A and then been dealing with making the Dialogue box system. Today I'm trying to add this detail to the script.
Are you saying to create the field for objectA and attach it to the field while script is still on objectA?
oh so this is on objectA?
The script is. The Dialogue box hierarchy which contains the button is on the same canvas, but not a parent/child with object A
so the close button a separate thing and NOT child of ObjectA that resizes?
closeButton has any scripts on it ?
no
could you show the hierarchy for the ObjectA that has script
Photo is objectA
The Dialogue script does have a field for the DialogueBox, but that shouldn't change parent/child relations, right?
what does Dialogue script do
It exchanges the respective objects/texts with the customized options set for each ```cs
object.using UnityEngine;
using UnityEngine.EventSystems;
public class Dialogue : MonoBehaviour, IPointerClickHandler, IBeginDragHandler
{
public GameObject dialogueBox;
public string dialogueText;
public Texture[] portraitTextures;
public void OnPointerClick(PointerEventData eventData)
{
SwitchTextAndPics();
}
public void OnBeginDrag(PointerEventData eventData)
{
SwitchTextAndPics();
}
public void SwitchTextAndPics()
{
dialogueBox.SetActive(true);
if (DialogueManager.Instance != null)
{
DialogueManager.Instance.DisplayDialogue(dialogueText, portraitTextures);
}
else
{
Debug.LogError("DialogueManager.Instance is null");
}
}
}
yeah doesn't seem to be touching the hierarchy but I have no clue what DisplayDialogue is doing
Small note is that ObjectA's script (ClickToBig) does include SetAsLastSibling in the Update to ensure that when it grows, it covers all other objects
yeah but is it putting it After RhiaDialougeBox or inside of it ?
When playing the game, I confirm that the Photo moves at the very bottom after RhiaDialogueBox
yeah that shouldn't affect Close Button scale then
btw colliders should not be used / needed on canvas objects
I thought that was required for OnPointerClick and DragEvents
OnPointerClick uses the Rect Transforms / event system raycast
(you can however use Physics Raycaster for colliders on non-ui objects, but thats another topic)
OnMouseDown is what uses colliders
Hello! I'm wrangling unsuccessfully with Unity's runner template. Something in Spawnable is resetting the positions. I disabled snap to grid and added the m_InitialPosition vector, but no luck!
only for world space objects (also the camera would need a physics raycaster), UI doesn't use colliders for any of that
Is there a way to lock a value of a specific object (closeButton) in public update?
Or maybe even in Awake\
wdym "lock a value"
Value of trans dimensions
If you don't want the value to change, don't change it
if you want that to happen conditionally, that's what if statements are for
if something is changing its size probably want to get to the bottom of it, instead of forcing size with update
why are unity event avoided? or at least all the guides i have seen using event use c# action delegate instead
I know that, but the issue here is that the Close button needs to tell the object to shrink when clicked. It is doing that, but the button grows with the object.
bandaid fix's dont last forever
UnityEvent is very good if you need modular/ inspector. No other real benefits over Action otherwise
Who avoids UnityEvent? They are widely used.
if you want to set up the listener in the inspector, that's the way to do it
that doesn't sound related to this "locking" question at all
set a flag..
i though the same, found it through the code auto completion, but have seen 0 guides using unity events
you are simply growing/shrinking the wrong object
They are used all over the place. They are different tools with different purposes than C# events though. ¯_(ツ)_/¯
if u ever used the actions on a button in the inspector you've used unity events
[SerializeField] UnityEvent somethingToDo// or make it public if you want other scripts to reference this
void Foo(){
somethingToDo?.Invoke()
someone fact check me.. are those unity events or regular events?
those are unity events, UnityEvents are serializable unlike regular c# delegates
I think the more "useless" ones are UnityAction
one drawback of a UnityEvent though is that anything with a reference can invoke it unlike a delegate with the event modifier which prevents other objects from invoking it
i have a shrink/grow menu system if it ever loads up
those aren't really useless, it's the delegate that UnityEvent uses
Ohh okay makes sense.. so they are not just a Unity version of Action
||redacted||
nah, they are just a delegate just like System.Action
||CIA jfk files||
the name does kind of make it seem like something special though
Unity prefix makes it sound important lol
assembly def is next
Could someone take a quick look at this with me?
another overconvoluted Unity Template
Mmmhm
eww
[ExecuteinEditMode] seems pretty risky just from the look of it
I don't know why they did that
ikr ? my first learning experience in unity was the FPS-MicroGame
it was not good to learn on
eww no kidden
beginners need bite-sized chunks
not the entire pizzeria
My gamedev class tossed this into our laps :d
most teachers are failed in the industry for a reason
I'm on exchange in Ireland for the semester -- having a very different CS experience, course is entirely self-guided and has no AI restrictions. His premise is, just get it done, which doesn't feel conducive to learning imo
not at all.
Unity has actual pathways that teach you from 0
these "templates" are meant to be "plug n play" if you feel like going through hours of someone elses thoughts and try to understand why certain things are coded a certain way
😭
idk you'd have to check all the abstractions there, like m_LevelDefinition and other externally defined items
is it possible to initialize it with a custom value?
just = desired value; after the }
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#automatically-implemented-properties
ok
Any ideas how should I point a projectile weapon directly to center of the screen/crosshairs?
Only things I found was for hitscan weapons
Well, you'd need to raycast from the center of the screen and make it look at that point
But that would be quite jarring
For now I just simply give the arrow an impulse force forward
So you are talking about rotating the projectile, not the weapon?
A lot of games actually shoot the projectile from the center of the screen.
You can however have a fake visual object for the projectile that originates from the weapon instead
The projectile is affected by gravity of course but I don't know how to make the aim satisfying
Like Hanzo from Overwatch
Do you mean, when hip firing/not aiming?
When it comes to replicating features, you need to really break down what makes up those things. You can't just say "Like hanzo", you need to actually assess what makes it "Hanzo-like"
That way you know what you actually want to achieve, and can explain it to people who have good taste in video games and therefore have no idea what that means
I really have a pet peeve for when people reference other games but don't even provide a link to said game feature
A video or something
Can't expect everyone to know every game
I explained it badly
What I struggle with is finding the correct rotation for the bow such that the crosshair can be used to aim and lead properly
Since the projectile has gravity, the crosshair can't really tell exactly where it will land
Because the arrow is actually physically fired from the bow's position
Unless you simulate its trajectory but that would be weird probably
Eventually the player would of course figure out the correct way to aim with some trial and error
I have set the forces to be realistic for a crossbow bolt
i guess everyone who atleast licked gamedev, or is playing games know who Hanzo is, from Overwatch
You guess wrong
Even if I know the character I don't know how the bow shooting looks in game
I think you overestimate how big of a property Overwatch is
So I'd have to go through the trouble of googling it/looking it up on youtube
Yea I just said the first bow aiming game that came to mind, will need to research more of them
The issue with not firing directly from the center of the screen is that where the cursor is pointing doesn't let the player know where the projectile will hit, since the distance of the raycast will be different based on how far the thing that you're looking at it.
It's the reason why in games like Marvel Rivals, you have to always aim a little to the right to hit things, because the characters stand a little offset and "shoot" from their model positions.
Hello, i keep getting this error, from a custom render feature when i try to build my game that says
Did you #if UNITY_EDITOR a section of your serialized properties in any of your scripts?```
It points towards this script https://hastebin.com/share/gajokizoqi.csharp , and i've tried alot to fix it and nothing works. Does anyone know anything about this?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Looking for Recommendation:
I have a DragDrop script that works great for standard objects. I have other objects which will need to be Dragged&Dropped as well, but the image that you see before clicking will substitute the image.
Looking for insight if I should modify the script I have to apply to both or should I make a different DragDrop script (diff name of course) to use for the image switching methods?
Hello, Im trying to have a gameObject bounce off my SolidObjects tilemap I have some code that is somewhat working however I dont think it is detecting hits fast enough. I have tried using OnTriggerEnter2D and OnCollisionEnter2D but neither detect anything, there's gotta be a better way so any advice is appreciated.
void FixedUpdate()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 1f, tilemapLayer);
if (hit.collider != null)
{
if (hit.collider.gameObject.name == "SolidObjects")
ReverseVelocity();
}
}
Wdym by "not detecting hits fast enough"?
So, It collides with my solid objects and actually reverses the velocity maybe half the time, I am assuming here that my raycast combined with the objects movement are causing it to miss hits
well I wonder why you are doing the raycast in a fixed direciton (down) at a fixed distance (1)?
Shouldn't you use the object's actual velocity here?
Ahh yes I probably should be doing that, would that help with always detecting the solid objects tilemap?
I don’t have a full picture of what you are trying to do, does it only collide on the bottom of the object? Or can it collide and reverse directions on like a wall or ceiling as well? Maybe try physics.OverlapSphere if you need to test all directions
Yeah so it’s pretty much just a projectile that’s supposed to collide with a big square and bounce around on the inside you’re probably right a sphere is better it was just something I threw together quickly cause I didn’t think I’d end up using raycasts
Well so if it is always raycasting down, it’s not gonna work on the sides and ceiling right? So you could use overlap sphere, or like the other person said have the raycast be in the direction of current movement. But raycast based on velocity direction might not work if like the projectile makes contact on its side / edge. Why aren’t you just using like a standard collider detection?
I’m unsure what you mean by standard collider detection
Put colliders on both the projectile and the (sides of) the square
Then use onCollision
I have a tilemap collider and a composite collider on the tilemap, and a collider on the projectile of course but when I was using onCollision it wouldn’t register collisions with my tilemap
you can be cheeky and right after u launch the projectile it can look towards where a raycast would hit from the camera thru the crosshair
Can you send screenshots of the colliders on both the projectile and what the tile map with so I can see the settings
And also the on collision enter code
Sure thing
void OnCollisionEnter2D(Collision2D collision)
{
if (((1 << collision.gameObject.layer) & tilemapLayer) != 0)
{
ReverseVelocity();
}
}
my character seemingly doesn't want to get down to the floor, how do i edit the sprite so that the hitbox matches up better
not a code question.
Try putting Pixel Perfect / Pixel mode in sprite editor
okay it kinda is though
because it's the box collider on his feet that stops it
okay maybe still not but it's not related to the sprite
where is the code part?
you're the only one who mentioned sprite lol
" how do i edit the sprite so that the hitbox matches up better"
so how do i make it so the extra box collider doesnt affect the height of the object
make it a child(actually this one doesn't work if parent has rb) or trigger
okay thank you
a box collider isn't code
one more issue, as u can see the collider is literally in the ground which has the "Ground" tag but the code doesn't activate (it's actiavted when i press w and it doesn't do anything)
what the heck
yes that is a foot collider called groudon
this code is so cursed im sorry
expected that
what is calling groundCheck() and why did you nest function in there
Why are you apparently manually calling a function called onCollisionEnter2D?
and this ^
cuz i dont know how to do it correctly
Also why is it a local function inside .. .yeah lmao
sorry went afk. Which one is your projectile? it looks like you have a rigidbody on your tilemap gameobject? The projectile needs both a collider and a rigidbody, whereas the thing that is being hit (tilemap) does not need a rigidbody
this is code beginner isnt it
Looking at the code examples in the docs would be a good start https://docs.unity3d.com/6000.0/Documentation/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
OnCollisionEnter2D should be its own separate function, not inside another one, and you don't call it yourself
also add a Debug statement in the first line of the OnCollisionEnter2D just to see if it is colliding but the layer mask it setup wrong
-OnCollisionEnter2D is a message sent to scripts, and it takes a Collision2D as an argument
- uppercase methods
- why are you nesting functions for no reason
well unity said that OnCollisionEnter2D isn't called
would be best not to nest functions like that.
"Declaring a function body inside another function makes it a "localFunction"
yes because you nested it inside another function therefore cannot be called by the normal Monobehavior way
isn't called?
Unity definitely didn't say that
Maybe your IDE said it
Unity didn't
and if your IDE said that it's most likely not set up properly
was as a warning in the console
probably a UNITY IDE error
you'd have to show the exact code and the warning that code created
but - basically you did something incorrectly
I think some examples and tutorials would go a long way
it would be hard to explain everything you are doing wrong and why
Ah the second is my projectile which does have a rb but I forgot to include it and the rb on the tilemap is there because its required for a composite collider. Also tried adding a log to the collision enter and nothing at all
you seem to just be winging it
is the tilemap actually in the tilemap layer?
that was the idea indeed
Should be yeah
double check lol
also if you set Collision Detection to continuous does that solve it? or is it already set
when you're at this level you should be looking for "how to do X correctly" rather than "how to fix what I am doing wrong"
theres a million examples of how to do what you are doing out there
If by in the layer we're just talking about the layer set at the top of the inspector then it is just wasnt sure I fully understood. And yeah tried setting to continuous hasnt changed anything
tutorial hell
really quite contradictive the advice im getting everywhere
whats the contradiction
people telling me to look at tutorials and other people telling me to not do that
idk who is telling you not to look at tutorials that is just wrong
The correct answer is look everywhere
i dont really think anybody said that
tutorials are great. relying on them later on isn't but in the beginning you should utilize them
You aren't going to find Tutorials that will do exactly what you want, and you should instead try to synthesize from multiple sources
tutorials will teach you the intuition and skills for how stuff works
dont copy the code, look at the code and try to understand why it does what it says it does
sorry without seeing the bigger picture im not able to be much help, this is a simple task so there is probably something glaring missing i can't see. The script that has the on collision code in it, it's attached to the projectile right lol?
finally made it update a text ui when clicking a button, pretty sure im a pro developer now 😎
dont use local functions
not until you know what you are doing
You got a function in your function
note how it says "localFunction" because you nested it
note how i realised i did it wrong hence the text under...
you probably didn't even realize you did use a local function becausr you haven't seen enough code examples to know how code usually works
which is why looking for snippets and tutorials online helps so much
it builds your intuition
No worries, I've shown pretty much all the code related to it which is why I dont get whats not working here, yep the script is attached to the projectile itself
but you haven't seen enough full scripts to know where that goes or what it does
missing basics of c#
Do you have any idea what might be missing?
problem is im missing understanding of unity functions
No, this is a C# one, not a Unity one
collisions aren't native to C# afaik
But functions and where to put them are
Your issue here had absolutely nothing to do with collisions
ye im just misunderstanding if it's a function or not
unity functions are c# functions with specific signatures
you gotta understand c# functions before you can understand unity functions
like the problem here is why does the function call for 2 variables which arent separated by a comma ( i know it's a varaible being defined now)

ok no
those arent two
go back to the very basics of C#
that's not two variables, that's a single parameter of type BoxCollider2D (which is wrong) and the parameter's name collision
did u read the whole sentence
i don't even understand your message
thats the TYPE and its name, its 1 thing
if you know it's a variable being defined, then, why is that a problem
because.. that's not what's happening
Variables in C# have a type and a name
Uh, it doesnt
it's not Python
There's only one variable there
yes and it made me more confused
the sentence doesnt even make sense. you say in the same sentence that you understand its a variable being defined..
okay so i see 5 people in a row stop their brain functions the second they get to half of the sentence
because the 2 halves are directly conflicting
or do you mean the "problem" is in past tense
yes that is indeed what is implied by "now"
whats the point of even bringing up that example then lol
Or because they're different people typing at the same time and not a hive mind
because that was the reason for the problems before
thats not related to what your issue was above, which is a basics of c# issue
and nowhere is it implied in your first sentence. the entirety of your first sentence indicates that it's a current issue
so know that we have clarification of that non-issue, let's move on
do you have any other problems you were gonna ask about
Nothing summons people to the chat like a good old fashioned argument
avengers assembling everytime a beginner gets a little too confident
this would imply the opposite of what you assume it to mean
a hivemind would all reply the same... like yall did lmao
They ask a question, get one answer, edit the question saying solved and then yell at everyone for posting after they edited it
never have i clicked edit in this sever
im so confused by this entire interaction....
let's just start a new one
anyone got any questions to donate
Or adding a second message saying "solved" rather than an edit
If you're interested im still struggling with my problem
Im now trying to get the projectile to register a collision in OnCollisionEnter2D but for the life of me it would collide with my tilemap collider
detecting hits fast enough
can you elaborate on what you mean by this?
is it phasing through the tilemap or something?
for the collision message, do you have the requirements for that message to trigger?
oh wait there are messages after that, one sec
Theres kind of a lot haha I can try and summarise if its quicker, basically yeah half the time if im ray casting It phases through even when I changed the ray cast to use the rb physics
ok, so you don't seem to have a dynamic rigidbody on either object
Ah so, Dynamic on both and it registers it also just bounced my tilemap off into oblivion haha
you only need one dynamic rb
you can leave the one on the tilemap static if you want (not sure if you need it at all)
if they are using a composite collider for the tilemap (which ideally they would be) then they do need the rb for it, but yeah it should just be static. the actually moving object should have the dynamic rb
Ok so seems to actually be colliding now, I cant believe I missed that, I think I tried it by editing the prefab root in my scene then instnatiating a new one. im an idiot but thankyou so much
ah, composite collider requires it, right? i remember my own tilemap having that rb too, just don't remember why lol
for future reference @edgy prism https://unity.huh.how/physics-messages/collision-matrix-2d
Thanks this will come in so handy im sure of it
digiholic also has this version lol #💻┃code-beginner message
not sure if it's their own or from some other resource
why should isTrigger not be ticked
Because if it was you wouldn't get any OnCollision messages
You would get OnTrigger messages
Hi, im having difficulties figuring interfaces. It seems like the 2 scripts wont link up
- Your IDE is not configured
- The error is talking about a third script called Interactor which you haven't shown and which presumably doesn't exist
What is Interactor
i was following a tutorial, ill try to rewrite some part thanks for the answer
You skipped something
Presumably
Wherever they define Interactor
ok ill rewatch the video
@wintry quarry @polar acorn thanks guys i was blindly following the tutorial and didnt realize it was referencing a script. I got it working
learn, research, practice. repeat
check pinned messgae for resources
practice, but make sure what you are practicing is something you enjoy. If you are practicing boring things you will not only not have fun but not be motivated to learn as much as you would if you enjoyed it
Go to school for it
computer science =/= coding
if you want to code, you can learn that not with college. college cs is theory and math
im literally doing my master's degree in CS right now
true
you learned to code while being at college for CS, separate things
"AI" can code, learn to be a good engineer / programmer
if you just want to code, not like advanced design, you can do that without college
It's a good way, that's all I'm saying
there might be an answer
Are you asking us whether you have a question?
No lol
punctuation
I wanted to ask
Is there any server api that can be used to upload pictures on the server and can be downloaded as well
And do not charge that much
It is because i want my game players to upload pictures as pfps in game
You can do this with many free tiers, including unity
Google drive is free if that suits you😅
lol
google drive is free i guess
But it is not a good solution
For a multiplayer game
Unity has PlayerData storage you can store the binary data of image
or a blob bucket like AWS , Azure etc.
Might want to research then. It's not like we have a text file with "the best free/cheap services for uploading pictures" on our desktop.
the problem is charges
Plus unity api doesnt allow large file transfers more than few 100 kbs
Nor can we access large files from the server of another user
I tried Playfab but we cannot get the other player's pfp
I found Google Firebase as a good solution
But they charge a lot
Both of them are hella expensive

all the ones mentioned have free tiers
if you're going over the limits you might want to better monetize your expenses if you plan such high traffic
The cheapest would probably be to rent a server and host your own api
i accidentally created magnetism
I plan nearly 10k traffic
and I dont know what to do
Digital Ocean has very cheap VPS you can get as much storage you want and they start at 3$
those require you to setup your own APIs like ASP.net
Hmmmm
I do not have a good spare pc that can handle requests remotely
Plus the country i live in is trash
i pay like 22$ for 15mbs internet speed
Ah, right. Well, Is it your code then?
and it keeps gravitating to the colliders
thats not what renting a server means
that seems reasonable
let me google it up
https://www.digitalocean.com/pricing/droplets#basic-droplets
Ionos is cheap too. These are cheap but come at the cost of having to setup your own APIs / infrastructures
heres a clearer example
this is within the same level as
a room where the rules are as follows
so wtf
oh
nvm
I found the rpbolem
there was a big ass box collider I forgot to reduce
@snow warren If I were you I'd start with the smaller free tiers with already setup apis for this this way you can use their auth systems, then if you need to scale up go from there.
Its easy to overplan
I will look up to it and see which one suits me best
Hello! I've got a weird technical problem that I feel has a fairly simple solution that I'm just missing. I'm creating a system where players tab an object and the info of that object appears through the canvas, specifically the object's icon and the player's notes. However, I'm having issues where there are multiple objects on screen with the "infoTabActivate" script, and the inputted text isnt saving to the list. i have each object's method as an on-end-edit listener but the console always activates every script at once but still returns nothng. how can i fix this?
https://paste.mod.gg/egckemsxirdb/0
A tool for sharing your source code with the world!
ah that fixed it, tysm!
i added text.text = playerNotes[index]; to the OnMouseDown() method to set the text to the pertaining object, but for some reason the text always stays the same regardless of the object
did i call it incorrectly?
each object has a specific index value set in inspector
Put a log in the function and see if it's ever getting called
which function?
OnMouseDown? im certain it gets called cause the rest of the method works properly
I know without specifics a proper answer can’t be given but realistically is the cost of creating tuples something I’m ever going to be worried about? (In the context of scales not big enough to justify dots or anything).
Was playing around with how I want to implement certain things and was considering a dict with a tuple as a key. Probably not what i’ll end up doing but got me curious
if the tuple is the key, could you not just define a class representing everything you need? the only time ive seen tuples used and kinda justified is when you want to return multiple values that arent grouped together otherwise.
you could profile it but i have a feeling like you'll not see any difference, unless you get to a significant amount of elements, at which point any operation would be slow
I like making tuples if I'm feeling lazy and want to group a few things together that will always need to be used at the same time later ln
Possibly but I’m trying to be super generic about it in hopes I can maybe integrate it into my little toolkit package that I use everywhere
how would using tuples there be more generic than a class?
you can accomplish the same things
Any more than 3 values and it ends up being easier to make a struct instead, a tuple with 4+ items means theres room for improvement
They're very quick to write in the moment
not necessarily a struct either
If I need two values together, there's not much harm in putting them into a tuple
and that isnt more generic, nor is a 5 second difference in writing code a real consideration. the question was more of a hint to saying it being a tuple doesnt help
They're pretty easy to improve later on, there isn't too much complication they bring that'd be difficult to refactor
if its written in thinking you'll refactor it later, just write it properly the first time! also this isnt really relevant to what they were actually asking
I might want a central static manager handling this rather than giving the relevant items all the sauce.
The tldr is I want basically a ScriptableStat’s system where eg. An Enemy has a list of ScriptableStat’s (lets say Health, Speed & Damage) and these scriptableobjects are used to retrieve the runtime editable value type value from this central manager by providing the scriptable stat and themselves.
I absolutely could store this kind of stuff on the scriptableobject but just considering potential routes to avoid storing runtime stuff on them if I can. And since I want this to be pretty generic and modular I don’t wanna burden the enemy class too much with all this
I'm only saying that I like using them for an immediate result, the use case definitely favours a class or struct. Nothing wrong with a lazy solution!
I don't think that tuples have too much cost too them
and still, where does using a tuple make this more generic than just using a class?
As far as I know, they're fairly light and cheap
also a note, ValueTuple is a struct. i honestly forget if ValueTuple or Tuple is used by default because I never use them. if you use value tuple, you should be aware of when to use structs as well because you really shouldnt need them often
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct
given your use case, i assume itll be boxed often
I have a Unity project on GitHub using Git LFS.
After making some commits, I reached my storage quota.
What are my options to continue working on the project? Should I buy more storage, clean up old LFS files, or is there another solution?
Also, I'm working on this project with one other person—how does Git LFS work in a small team?
Do both of us need to set it up individually, and how does the storage limit apply to us?
Can always just stick to placeholder assets then disperse the assets later to the one building the project in chunks
audio and textures usually the main culprit and easy enough to substitue till later
Hi, I am working on 2 projects that use the same asset that behaves differently(asset is made by me).
In both projects, I wanna extend the partial TrackAsset class.
I included the assemblyref and placed the thing in the correct namespace, however, in one project it works fine and in the other it doesn't.
I have very little experience w assembly def/ref so I would appreciate somebody helping me.
My advice, switch to gitlab if possible.
You get much more storage(10gb iirc) and a lot more bandwith.
please @ me if you are able to help
ok, asmref was working correctly but rider was dying and not getting updated or sm...
does anyone know why like when i finish this level and it shows the win menu, i click on next level and when i go on the next leve, i start with the amount of money i left off in the last game not 100 like what every game i have starts with
show relevant code
!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/, https://scriptbin.xyz/
📃 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.
you can bookmark one (or more) of those sites so you don't need to use the bot command every single time you want to share your code
level manager script it handles the currency and lives https://paste.mod.gg/vjyaiytqzvxo/0
A tool for sharing your source code with the world!
this object is DDOL which means it is going to stay alive when you switch scenes and keep its current values. Start is also only ever called once during an object's lifetime, so it will not be called on this object again after the first time
oh who do i drag a ddol into a scene?
huh?
how do make the levelmanager stay in the scene?
I split an array and am iterating through it, but I cannot for the life of me figure out what this little trailing blank is at the end. Is it a whitespace? is it NULL? WHat is this?
don't make it DDOL if you don't want it in the DDOL scene. but it simply being in that scene isn't the issue, the issue is that you are expecting a new instance of that object or for it to call Start again, neither of which are possible due to your currnet code
are we supposed to just guess what the actual context is or . . .?
oh is there like a duplicate of the levelmanager causing the levelmanager to stay in DDOL?
did you not read your own code or what?
I used Json.Split('}') on a json string that I pulled from a json file that was created to hold an array of objects(the array was parsed through and each object serialized).
The Json split mostly worked, but to parse through the string[] created with Json.split I'm using a foreach loop, and I'm finding that there is just a blank(see image), and I don't know what character that is, if any.
are you printing an entire string? if so, maybe check if it is null and if not print its length. you haven't shown actual code so naturally i can only guess at what the issue is
I'm printing each string in the string[] created from splitting one big string, but I'll go with your suggestion because I just want an easy fix
that's not going to "fix" whatever the issue is, it's just going to provide more context about what you are printing
exactly, and then the easy fix will be checking if that string is that context, if so, continue;
why are you even parsing this json manually anyway? can you not create an object and just deserialize to that object
Is that possible with a json list of the same object?
Is there no way to pass bools by reference to a coroutine? or anything by reference for that matter
What's really funny is that I finally got it to work, and now I'm most likely going to learn a more efficient, more reliable way to do this entire process
that depends, if the root of the json is the list then you need to make sure to use Json.NET or some other json library besides JsonUtility (which is the json serializer built right into unity)
oh is causing the levelmanager to be on dont destroy on load?
private void Awake() {
if (main != null && main != this){
Destroy(gameObject);
}
else{
main = this;
DontDestroyOnLoad(gameObject);
}
}
coroutines cannot have ref parameters
rats
yes, but again, it simply being in that scene isn't the issue. it's the fact that you keep it alive and destroy any other instances then expect it to be a fresh instance.
so you probably don't want it to be DDOL, but you were focusing on the wrong aspect of it being DDOL
I created the json by doing a foreach loop through a 2d array and serializing each object within. they are the same object. Would the 'root' of the json be a list of obejcts or is it different?
did you create the json manually too? why are you not just using a json library for this?
again, the issue is not that it wasn't in the scene, the issue is that you were keeping the same LevelManager around but expecting it to act like a new one when you restarted and also destroyed any new instances that were created by reloading that scene
no I'm using json.serializeObject for the objects
and i couldnt' serialize an array of objects because it breaks
that is a limitation of JsonUtility, it does not support collections as the root object, but you can just put the array into some wrapper object and de/serialize that
ah so that's what they meant, I put the basic object into a wrapper, not the array
woops.
Can we ask for help in here?
yeah brother
I'm trying to make a score system and I'm not sure how to go about it.
(I am on Unity Editor with C#, and I'm basically a beginner)
More detail:
I'm making a game that has a similar foundation to Agario in the sense that you eat things and grow in score and size.
I need to make a score system where each food has its own different value, and when eaten, that value is added to a player's score.
What I would want to do is have each instantiated food prefab have a easily assignable score value, and this to be acessed in my food eat script.
I have this right now below where each food is automatically 1 and this is triggered on contact with the food. I want the "1" to be a variable that matches the collided food's value.
playerFoodScore = playerFoodScore + 1;
I want it to be
playerFoodScore = playerFoodScore + collidedFoodValue;
The "food" is 3 different prefabs that are randomly instantiated into the game.
I do not know how to assign this value to each different food prefab and have it detected when my player collides with it. If anyone is willing, could you help me walk me through figuring this out?
I can provide more detail or show more detail if needed. I don't think I'm allowed to ask people to join calls on this discord server is that correct? If we are allowed then I can do that gladly.
you should have a component on the food itself. this component will have a value saying its worth, when you collide with something, try getting the food component and then just read its value
!code for how to paste code in the future
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Thank you I will come back and let you know where I am
That makes sense
how do i edit the name of all variables with same name in visual studio,
for eg i have float speed = 10f; Move(speed);
how do i edit the name of variable speed everywhere in the code
wait why you deleted
mixed up vs and vscode
ah, i think this fits better actually https://learn.microsoft.com/en-us/visualstudio/ide/reference/rename?view=vs-2022
Keyboard
Press Ctrl+R, then Ctrl+R. (Your keyboard shortcut may be different based on which profile you selected.)
Mouse
Select Edit > Refactor > Rename.
Right-click the code and select Rename.
what are you trying to do
is it not doing what you're intending it to
no
or are you just asking for tips on how to make it better
i am trying to play walk animation while moving
it is not playing it
stuck on idle
so i asked whats wrong
pretty sure PlayerBody.angularVelocity is the players rotational speed
and from the looks of it the player shouldn't be rotating
I got it working thank you
it was easier than I thought it would be I think I was just scratching my head too hard
still, its an or so it should work
what should i use for getting movement velocity
Movement() is being called in Update() right
yes
linearVelocity i think but i use traditional character controllers
i mean i'd just use Input.GetAxis("Vertical") instead of Input.GetAxis(InputAxis.Vertical) but if the character's moving that's not the problem
InputAxis .Vertical is a const they've made
i see
its a var though
i have never used that panel in my life 💀
you mean a static variable ?
i should change it to const cause it is constant
you havent made a game with animations?
so is that part of animator running
am i doing something wrong
it is stuck on idle man
i've never reached the animation part
stuck as in keeps playing or just doesn't go into other animation at all
normally i save stuff like that for after the game's working
doesnt go
idle has no animation btw
yet
put debug.log first inside that if else statement
ok
what is the exit condition walk to idle
shall i debug using visual studios debugger?
what is supposed to do ?
its printing
on console
which part of if statement
you type your username into the text input field, then hit enter, and then it sets your username on the mv component and hides the UI element
which isn't happening at all
have i set up animator the wrong way?
submit button?
its one giant if statement with bunch of conditions and an else so i dont know which part
like have a UI element that submits instead of waiting for the submit key to be pressed?
the part where you set animator bool to true
GetButtonDown Submit ? are you pressing the keyboard button for "Submit"
yes
ok but please don't send ss of codes, use 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 chat script was firing)
so text is not focus?
text should be focussed (iirc IsFocused detects if im currently typing in it)
breakpoint or Debug.Log(text.IsFocused). easy checks
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float speed = 100f;
[SerializeField] Rigidbody PlayerBody;
[SerializeField] Animator animator;
void FixedUpdate()
{
Movement();
}
void Movement()
{
PlayerBody.AddForce(transform.up * -Input.GetAxis(InputAxis.Horizontal) * speed * Time.deltaTime);
PlayerBody.AddForce(transform.right * -Input.GetAxis(InputAxis.Vertical) * speed * Time.deltaTime);
if(Input.GetAxis(InputAxis.Vertical) < 0f || Input.GetAxis(InputAxis.Vertical) > 0f ||
Input.GetAxis(InputAxis.Horizontal) < 0f || Input.GetAxis(InputAxis.Horizontal) > 0f ||
PlayerBody.linearVelocity != Vector3.zero)
{
animator.SetBool("isWalking", true);
Debug.Log("check animations");
}
else
{
animator.SetBool("isWalking", false);
}
}
}
class InputAxis
{
public static string Horizontal = "Horizontal";
public static string Vertical = "Vertical";
}
so its printing yea?
are you holding down the keys the entire time?
yes
did you show the exit transition walk to idle
yes it is, but it turns false the frame i hit enter
switch up the order of && condition or make a different one
show that
is it ok to set up animations in fixed update?
I would use update but it should work
this is idle to walk. what about other way
invoking with 1s delay worked
seem sketch
ty
btw you should remove * Time.deltaTime on rigidbody AddForce
thats not correct to do
ok
the animator instance has this controller and you referenced the correct one ?
leme check
you know what
let me share the project with you
maybe you can see whats wrong
screenshot should be fine if you show specific thing, there aren't many things that can be wrong
if its humanoid and has an armature then it should probably have an avatar
without the animations, check if its actually going into the states which seems likely now and probably wrong setup of rig
its a walking bulb
can you have a look at my project
i will share you
I would check this first to eleminate the possbility that is code
#💻┃code-beginner message
have the object with that animator selected, drag the animator in a side by side tab game view
my avatar is empty
would still check the animator states
its the animator controller
it is not playing animation even without conditions
why is this so confusing. isnt unity supposed to be easy
"easy" is relative. if it's hard with the given tools, imagine how hard it'd be without any help 🫠
if it's not a code issue, check out #🏃┃animation
Unreal is easier to setup materials and lighting but runs crap on my laptop and Its way harder to learn
It's an issue of setting up animations through code
Internet is a blessing and curse.
do you mean like, animator parameters? or the actual animator states?
Switching between animation states
Is what I meant
And it's done through code so I came here
directly or via parameters?
Hi, anyone know to use visual script?
probably people in the #763499475641172029 channel
im getting lost every once
I'm following an FPS player controller tutorial using Unity's input system. In the tutorial, the person wrote 'e' in their code, but they don't really explain what it is. I've never seen it before. Does anyone know what it is?
I don't think 'e' is a reference to anything either
it's called i think a lambda expression https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions
You use a lambda expression to create an anonymous function. Use the lambda declaration operator => to separate the lambda's parameter list from its body.
Is that not the '=>' ?
it is the =>
So that's the 'e'?
and e is the parameter
Ooh okay
Man, Lambda is confusing
In the screenshot above, how does the 'e' know what it's referencing?
because you're adding the method to the performed delegate (i think it's called delegate? not sure on that one) of the action, and it passes in only one argument
So would the 'e' reference any of these inputs (W,A,S,D)?
When any of them are pressed
e references the CallbackContext, on which you can use the method ReadValue<Vector2>() to get a Vector2 containing the direction of the input
So when I press an input key, e read the Vector2 value which is applied to my input_movement value and then added onto the input character movement value?
when you press an input key, it calls the lambda function which reads the value and sets input_Movement to it
Why is this += then? isn't that adding the input_Movement value back onto the defaultInput.Character.Movement.Performed value (if that's even possible?)?
the performed value is a delegate, which is sort of like a set of methods that gets called whenever it's invoked, https://youtu.be/J01z1F-du-E?t=169 (timestamped)
▸ Learn how to CODE in Unity: https://gamedevbeginner.com/how-to-code-in-unity/?utm_source=youtube&utm_medium=description&utm_campaign=events
Learn how to create event-based logic in Unity, using Delegates, Events Actions, Unity Events & Scriptable Objects.
00:00 Intro
00:39 Event-based logic in Unity
01:56 The Observer Pattern
02:49 Delegat...
+= means you subscribe to the action, so that every time the event on the left (...performed) is invoked, the lambda on the right will be invoked too
it's not adding the value, it's adding the function
So the thing you most often see in C# is a method signature that helps describe the parameters tha a method will accept.
For delegates/events the signature is where the delegate is defined, not where you subscribe ( += ) or unsubscribe ( -= ) to it.
Here's the definition of the performed event:
Which shows that any callback that subscribes to this event will receive a CallbackContext. In this particular case a Lambda expression is used and the callback context received here is named e (left side of =>) by the lambda expression for the lambda expression to use in the code it executes (right side of =>)
Are lambda expressions used to avoid having to write out entire methods and to keep things compact?
Yes
In Java these constructs are known as "Anonymous functions" because they don't have a defined signature
The general idea is "this is the only place you will use this code, so let's skip the many lines of a method"
How are delegates/events different from methods?
Assuming you mean how are "Lambda Expressions" different from method:
Only syntactically, for all intents and purposes
There's probably more to it if you dig deep into it
delegates/events are multiple methods that all get called when the delegate/event is invoked
^ Yeah delegates/events are just "a list of methods", but they are variable in the sense that you can add or remove methods from that list when the code/game/app is running without changing the code itself.
Why do I see complaints from people taking the course on unity learn about beginner scripting among the comments? Isn't that the right approach to learning coding?
So for example, you might have a system in your combat code that handles damage and health of a character in the game, but you might want to have your UI and Audio systems do things whenever damage is done to a Unity.
In this case I have simplified the delegate so it has no parameters/arguments because here I'm focusing on showing how a delegate/event changes how code is linked.
Imagine the following code:
public class UnitStats
{
public int Health;
public void TakeDamage( int damage )
{
Health -= damage; // Simplified code for example only
UIManager.UpdateHealthbar();
AudioManager.PlayOuch();
}
}
This is what's referred to as "Hard coupling" with direct hard-coded links between two systems. There are many reasons why you might not want hard coupling. I'll explain that a bit after completing the example of what events are and how to use them:
Another way to "loose couple" the involved systems is by having the combat system post an event and for other systems subscribe to that even if they are interested in it:
public class UnitStats
{
public event Action OnDamageTaken;
public int Health;
public void TakeDamage( int damage )
{
Health -= damage; // Simplified code for example only
OnDamageTaken?.Invoke();
}
}
For this to affect other systems they have to first subscribe to the event:
public class UIManager
{
public void Start()
{
PlayerCharacter.UnitStats.OnDamageTaken += UpdateHealthBar;
}
public void UpdateHealthBar()
{
// Healthbar updating code here
}
}
This essentially does the same thing - well only for the "PlayerCharacter" in this example. But it's more loosely coupled.
So e is like the name of a method that isn't being created in the moment that the defaultInput.Player.Movement.Performed is called?
e would be the name of the first argument that a method would have.
Lambda expressions don't have "names", those are kinda skipped.
e is the name of the parameter
{
public event Action OnDamageTaken;
public int Health;
public void TakeDamage( int damage )
{
Health -= damage; // Simplified code for example only
OnDamageTaken?.Invoke();
}
}```
What are you invoking here?
In the example above
Exactly! Great question!!
Events invoke any method that has been subscribed to it earlier
So any method that has been added like so: OnDamageTaken += ....
-# just don't miss the plus
In this case that would be the UIManager's UpdateHealthbar since that would have been assigned during Start()
But assume there would also have been an AudioManager with a similar Start() method to the UIManager in which case both the UIManager and the AudioManager would have methods that would be invoked in that case.
To subscribe is += and unsubscribe is -= ?
Correct
yea
And it's always a good habit to make sure "if you subscribe once, make sure to also unsubscribe later"
So when you invoke OnDamageTaken, it calls the UpdateHealthBar method. Do you have to put a ? when invoking?
^ So the ? during invoking is just a good habit because it's the same as doing if(OnDamageTaken != null) first. With events this translates to "check if anyone subscribed yet"
If you try invoke an event with no subscribers then you will get an error. The ? avoids that.
Lambda expressions only 'exist' when they're being called, right?
It's like a method that doesn't exist until it's called
^ You can think of it that way. It does exist in memory as long as the app is running I think, but for you, the user, you cannot re-use that expression elsewhere.
And when I mentioned earlier that these expressions are nameless, i.e. why Java calls them "Anonymous functions" is because without a name you cannot call them. So for that intent they do not exist outside of that delegate.
So in this example, the 'name' (or really delegate), is 'e'? and that's what's used to call the lambda expression
^ I'll convert this to a proper method for you so you can do a direct comparison:
defaultInput.Player.Movement.performed += SetInputMovement;
void SetInputMovement(CallbackContext e)
{
inputMovement = e.ReadValue<Vectro2>();
}
This does the exact same thing as the code you have already
So this should answer what e is I hope
The main thing lambda expression does here is to skip the naming part SetInputMovement that I came up with for this example. Everything else is the same
How does inputMovement affect the value of SetInputMovement?
The above example is still using an event/delegate but is no longer using a LambdaExpression
inputMovement is just some variable in your class somewhere. The code that is executed in both cases is "assign the player's input to the inputMovement variable"
SetInputMovement is just a name I came up with for the method/function that I thought would accurately describe what the code inside attempts to do
Okay, I think I'm getting it
So if you did defaultInput.Player.Movement.performed -= SetInputMovement;
It would stop setting the value of inputMovement, because that method is no longer subscribed to that event
^ correct
because that's what the lambda expression has
the e is the parameter, it just isn't typed because the compiler can infer the type for lambdas
Probably makes more sense if you take a closer look at performed
But that example isn't using a lambda expression
it's the same as the lambda experssion but without using a lambda expression
That is the signature that the performed event is defined with and it's the type of the argument that all subscribers to that event must have to be valid subscribers. If you try to subscribe with a method that doesn't have a CallbackContext parameter you will get an error.
And in my earlier example with healthbars I didn't have to because I defined a simpler event. I used public event Action ... in my definition, but with Unity's performed event the type is public event Action<CallbackContext> ...
If you have a method, that you want to be potential subscribers to multiple events, would you have to put multiple signatures?
^ You would need multiple methods instead, unless all events use the same signature
There has to be a perfect match between the event's definition/signature and all methods that try to subscribe to it.
You can't have any extra parameters in the method, nor can you have fewer. And the type of the parameters has to match exactly.
i changed my character model from a capsule to a proper model and now it can jump before it reaches the ground, any ideas?
(unless you compose your own wrapper class)
I think your collision mesh is probably misalligned with your new model
Okay, I think I'm getting it. it's super confusing
i fixed that, the model touches the ground, but after the first jump i can jump again before it reaches the ground
nvm i figured it out
what was it?
the script i use, uses half the playerheight to figure out when its touching the ground, and apparently i needed to keep the original, smaller playerheight, instead of the new taller one
So a good way to explain how "starting" and "stopping" subscriptions would be useful is by hypothetically extending my HealthBar idea:
Imagine that you only want your UI to show the health of a unit you have selected. If you deselect that unit, or select a different unit, you don't want the healthbar to keep updating when the old unit takes damage.
Example
Here's the old method:
public class UIManager
{
public void Start()
{
PlayerCharacter.UnitStats.OnDamageTaken += UpdateHealthBar;
}
public void UpdateHealthBar()
{
// Healthbar updating code here
}
}
Now imagine this instead:
public class UIManager
{
public void OnUnitSelected( Unit unit )
{
unit.UnitStats.OnDamageTaken += UpdateHealthBar;
}
public void OnUnitDeSelected( Unit unit )
{
unit.UnitStats.OnDamageTaken -= UpdateHealthBar;
}
public void UpdateHealthBar()
{
// Healthbar updating code here
}
}
So now instead of subscribing on Start, we subscribe "when the UI is interested in the Unit's damage taken"
This is one of the benefits of Delegates/Events (note that we're not talking about lambdas in this example, just delegates/events).
Delegates are variable - not hardcoded. You can add/remove systems that are "interested" only when that is relevant.
And we could make a hypothetical scenario for the AudioManager too - where the AudioManager is more concerned with whether a Unit is within the camera view or not. Perhaps it is subscribed to multiple units at once since there can be multiple units in the camera view. I won't make example code for this, I think you get the idea.
Another benefit - and this is why Unity makes you have to learn this now - is that a system using events only needs to be concerned with itself, and does not need to know about other systems that are interested in it.
So basically the UnitStats code does not need to be concerned with UI or Audio. And that is good code design. Similarily, Unity's code should not need to be concerned with your code. It's a one-way relationship. It's your code that is interested in what Unity is doing. It's the UI that is interested in the health change, not the other way around. Imagine if you had to dive into Unity's huge code libraries to add calls to your own methods inside there? That would be horrible. Instead you can just add this neat one-line subscription in your code.
Events allows an external system to get notified when an internal system does something. Another perspective is, you can make a system today that has the ability to communicate with a system made in two years without having to go back and update today's system.
im trying to make a script that locks the y rotation of my player model to the y rotation of an object in the scene, but im having trouble figuring out how to write it
this is what i have so far
reminder for both of you
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
oh cool
You want to copy another object's y angle to this object?
yes
pretty sure you can do transform.eulerAngles.y = object.transform.eulerAngles.y
This sounds like something that perhaps the Contraint components can do 
That^, except you need to make a separate variable instead of directly modifying it
do i do public Transform orientation; at the beginning?
Vector3 euler = transform.eulerAngles.y;
euler.y = object.transform.eulerAngles.y;
transform.eulerAngles.y = euler;```
yea that
Euler angles have some issues like gimbal lock but for most situations like this it shouldn't matter
Assuming you have a "traditional" game where world up is always the y axis
im getting a lot of red squiggles