#💻┃code-beginner
1 messages · Page 190 of 1
how come all three buttons go to the same photo?
im gonna roll out my own splines system tho..
it is a premade asset
so ill just 86 this one while im here
what does this have to do with code and what do you mean by "go to the same photo"?
b/c u probably moved the graphics
and the parent container has the same rect/ anchors
very good chance it has an assembly definition
I don't know how find assembly definitions
just look in the folders
it's a file with a puzzle piece icon
.asmdef extension
search for t:asmdef in the project window
and filter to the folder you're currently in
I have three photos and the buttons all go to the same photo
what does it mean for a button to "go" to a photo?
i just explained it to u..
and again what does it have to do with code?
the parent (rect transforms) and anchors are the same..
u just duplicated hte same button over and over
there's a few
I'm making a 360 virtual tour
and moved the graphics
that's not an answer to the question...
Well whatever asmdef your code is inside, you need to add TextMeshPro as a dependency to it.
Or just move your code outside that folder entirely
you did this.. thats why its showing the same button.. (the rect IS in the same place)
you only moved the stuff inside
what's the attribute called?
what attribute?
when I click a one of the three buttons it should go to a 360 photo each button to a different photo but all three are going to the same photo
I mean, how can I add it
there's a list of dependencies in the asmdef, add TMP to it
are you deaf?
or blind?
{
"name": "fps.Game",
"references": [
"GUID:1826c0224c0d048b88112c79bbb0cd85"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
no
look at it in the inspector in Unity
not in a file editor
oh I see
And how does the button "go to" anything
You haven't shown anything in your screenshots about how the buttons are configured i.e. their click listeners so it's very hard to help.
its focusing on the RECT TRANSFORM!!!... YOU moved the graphics buit didnt move the actual Object
I'm not sure if they're saying that or if they're saynig someting about when they click the button in the game
yea they're talking about the Focus of the window im pretty sure..
sorry
i could be wrong.. lets listen.. 👂
this is like the same screenshot
you have to show how you configured the on click listener
You were told what to show and then took another screenshot that also doesn't show it
ya, now im curious of what he means by "go to another button"
click listener what's that?
the thing that controls what the button does when you press it
it's the first thing you would look at if you're worried about what the button is doing when you press it
You should probably follow this tutorial to understand buttons in Unity:
https://learn.unity.com/tutorial/creating-ui-buttons
Where have you told the buttons what to do
see.. thats why i thought it was the focus / bad transform positions.. i haven't even seen a event listener
Is there a way to use "OnTriggerEnter" and "OnTriggerExit" on objects that are not the parent of the script?
that question doesnt make sense
you mean objects that the script isn't attached to?
it trickles down the hiearchy..
Yes
but not some other object entirely. i dont think it works that way
no, it doesn't trickle down
if it has a rigidbody and colliders it does doesnt it?
Rigidbodies can receive trigger and collision events involving child colliders
OnTriggerEnter has to be either on the object with the Collider or the object with the Rigidbody. It won't work anywhere else.
Thought you wouldn't waste your time hmm?
Hmm.. is there another way of doing colision detection?
explain your actual problem
What are you trying to accomplish
not your attempted solution, mind you
Want to add text to the gui when a player walks into a zone
OnTriggerEnter seems like the most straightforward way. What's the issue with it?
Put a script on the zone object.
And. have the variables attached to the prefab
i don't know what that means
^ good solution. (keep it simple)
when you register a collision you'll have access to anything from each other..
would that be in the code?
I think you need to follow the tutorial you were linked to.
I linked you to the tutorial for how to set up a button. it explains how to set up the behavior of the button
Here's a video if that's more your thing: https://www.youtube.com/watch?v=J5ZNuM6K27E
have there been recent updates to the UI system or is it basically the same it's been for like 7 ish years?
There's a whole new UI system
UGUI is basically unchanged
a new new one?
UI Toolkit is all new
when is that from?
when you make a button you can set up what it does when you click it straight from the inspector..
but usually you'll want to code in the behaviour in a public function from some script.. you drop the object w/ that script into the slot and pick the function (w/e u want the button to do)
I'm not sure what you mean by that
idk maybe ~5 years ago? It's still a work in progress
but yea, watch some Button Tutorials and stuff.. you wont regret it.. considering buttons is a big part of games
why can't you just put a trigger collider and a component with OnTriggerEnter together?
what about that isn't working for you?
if you explain that, we can probably help you
Well it would be preferred if properties could be easily accessed from the prefab not three objects down the tree
so there was imguig, then ugui, then they made a whole new one? hopefully it's easier to use than ugui, as that was pretty convoluted...
The prefab root should have most of the logic on it.
void OnTriggerEnter(Collider other)
{
// Check if the colliding object has an Enemy component
Enemy enemy = other.GetComponent<Enemy>();
if (enemy != null)
{
// Call the Damage function on the Enemy component
enemy.Damage();
}
}``` i simply mean.. when unity detects a collision / trigger enter or w/e *you'll then have a reference to the thing you hit*
like in this example we take the `other` variable and check if it has an Enemy script.. and if it does we can call a function from it.. (so if you had variables or w/e you needed, you'd be able to get that stuff when the collision takes place)
The collider object (which is a child) should have a component whose only job is to notify the root component about the trigger
Nothing else.
Only do this if this actually makes sense, of course
^ and thats what i meant by keeping it simple..
That's why you make a script on the root of the prefab that has functions for all the things you need to do to interact with it
If the prefab represents a single zone, or is fundamentally tied to a single zone, then go for it
If the prefab has many zones, then it doesn't really make sense to have zone configuration on the root
you'd have zones configuration
i guess :p
designing interactions can be tricky..
i always take a bit of extra time to jot down what alls on the object.. and how i could keep things seperate.. like in the zone example, id probably put the trigger code on the trigger itself.. and keep it away from anything i got going on in the player..
but like Fen said.. its different for everyone..
whiteboard it!
facts!
Bomb: https://gdl.space/kuviwogoja.cs
Player collision: https://gdl.space/azaruhagay.cpp
Anyone know why the bomb sometimes fazes through? it happens with an unpreditable frequency... but seems that one of the bomb has to hit the player before it can happen?
😔 feels like the same efficiency as talking to self
talking to yourself can also be effective
If there is a list of a mono behavious (for example, List<Item> and Remove is used to remove an actual instance, will the actual instance be deleted or just the first element because it's the first of the type?
lol.. RubberDuck FTW!
Nothing is destroyed
not if you self reflect negatively
The first matching reference is removed from the list
It removes the element from the list, that is all
you're throwing out a post-it note, not the actual object
Also note that destruction is a very specific Unity concept
C# objects in general aren't "destroyed"
Once every reference to an object has been lost, the garbage collector can clean it up. That's it.
Hi, when you use transform.y for example, it uses the y world location, but I was wondering if it was possible to set manually the y attribut of a transorm
. Like if I want the transform.y the correspond to a given vector
transform.y does not exist. transform.position.y does exist.
the most simple way ive ever seen GC explained
Well, for one, there's no such thing as transform.y
You can't set transform.position.y directly because transform.position returns a copy of the position, and modifying it would beuseless
why does it matter?
You can save transform.position in a variable, modify the variable, and store it back in transform.position
it doesn't really matter here at all!
Uh yes that's what I meant my bad
but AA talked about an instance being "deleted"
so I wanted to clarify how things can even get "deleted" in the first place
It's not really an issue of mattering, that's just how C# works. It clears up memory for you when nothing is still referencing something so you don't need to keep track of memory allocation
It's not like you can change that
But it would be better to yield the index of the object and use the index to delete a mono behaviour from a list, right?
Well bad things would only happen in edge cases?
Vector3 initialPosition = transform.position;
initialPosition.y = 2.0f;
transform.position = initialPosition;``` How *I* typically modify positions
I don't know what you're describing.
"yield the index of the object"
If you want to remove an object from a list, remove it
That's it
theList.Remove(whateverYouWantToRemove)
I think he means List.RemoveAt
You could indeed get the index of an object, then use that index with RemoveAt
it would be essentially equivalent to using Remove
I guess I'm concerned about whateverYouWantToRemove being of a type that Unity can't differentiate from other objects of the same type, therefore removing another object if Remove(whateverYouWantToRemove) would be called
Unity has nothing to do with List.Remove
it does not remove by Type it removes by Instance of Type
The list looks for the first element that equals the object you provided
If two objects of the same type can't be differentiated by Remove then it doesn't matter which one is removed
Because both are the same object
or your Equals method sucks
Every kind of object can be compared for equality (it's often just reference equality)
I think we have a fundamental misunderstanding of C# here
If you've set up a custom equals method that returns true for two objects, then by definition those are the same object. You've just coded it to be so
true!
Whether or not you were supposed to mark those two equal is a different matter
Let me share actual code because it's a bit abstract now:
public class Bee : MonoBehaviour {
public Apiary home;
private void Reproduce() {
var newBee = Instantiate(this);
home.Add(newBee);
}
}
So here the home has the new instance of the bee.
public class Apiary : MonoBehaviour
{
private readonly List<Bee> _beeStock = new();
public void Add(Bee bee)
{
_beeStock.Add(bee);
}
}
Can I now use Remove of List to remove the exact instance of Bees I want?
Yes.
Ok :)
MonoBehaviour uses reference equality (as do most reference types)
Reference equality is strictly based on whether two variables refer to the same object in memory
This isn't a "Unity differentiating things" question, it's a C#/List question, and in C# you can define how your class defines equality. By default it will be reference equality.
Ok
Value types are different, since they, by definition, aren't references
you know, I'm not actually sure how that behaves
i tend to implement IEquatable if I'm going to be doing anything involving equality with a struct
can you help me out? in my game player has animations and when i press down shift and hold it it sets animation Run to true but when i put my finger up and dont t click anything Run stays true
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerScript : MonoBehaviour
{
public float moveSpeed;
public Rigidbody2D rb;
public float walk;
public Animator anim;
public float walksSpeed = 4;
public float runSpeed = 9;
public bool run;
// Start is called before the first0 frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
walk = Input.GetAxisRaw("Horizontal");
bool isRunning = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
if (isRunning == true)
{
anim.SetBool("Run", true);
}
else if (isRunning == false)
{
anim.SetBool("Run", false);
}
if (walk > 0)
{
anim.SetBool("walk", true);
transform.rotation = Quaternion.Euler(0, 0, 0);
}
else if (walk < 0)
{
anim.SetBool("walk", true);
transform.rotation = Quaternion.Euler(0, 180, 0);
}
if (walk == 0)
{
anim.SetBool("walk", false);
anim.SetBool("Run", false);
}
rb.velocity = new Vector2(walk * moveSpeed, rb.velocity.y);
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
lmao
TRIPLE KILL
please share that on a pastebin site (:
okay
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
dont check a float for equality
floats dont work well when you do ==
It is unlikely that your value will be exactly 0. Due to imprecision, it could be something like 0.000000002
i checked it but it is 0
You can use Mathf.Approximately to see if they're close enough
https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
yield return new WaitForSeconds(0.7f);
//DoDamage();
BSM.PerformList[0].choosenAttack.Activate(this, ChosenAttackTarget.GetComponent<UnitStateMachine>());
yield return new WaitForSeconds(0.25f);
is there a way to tell to coroutine to wait until the BSM.Perf... is done executing? Or is it waiting for it by default?
I don't know what that thing is
If Activate is a regular method, the coroutine will completely execute that method, then continue on the next line (as per usual)
Code can only run one line at a time ever. Once it enters that Activate function, that's the only thing it's doing. It will execute the entire function then leave
Even if that Activate runs another coroutine? The reason I was asking is because I've heard that coroutines do run simulatenously?
not true
If Activate does nothing but start a coroutine, then it'll return after starting the coroutine as per usual
If Activate returns that Coroutine object, then you can yield return it to wait for the other coroutine to complete
wait, starting the coroutine and running it until the first yield
The default behavior of code is that the called function executes in its entirety before continuing. This only changes for async functions and coroutines
Ah, true
Coroutines run one line at a time like everything else. When it hits a yield statement, it'll defer back to where the code was before it was called. It gets checked periodically to see if the yield condition is done, and if it is, it picks up where it left off
I originally thought that running an IEnumerator method intrinsically did that. No, that's just Unity calling MoveNext on it immediately.
okay, thank you.
thank you sir and madam
also, they don't run "simultaneously" -- each MonoBehaviour has a list of active coroutines
Unity will go through all of them every frame, one at a time, and resume each coroutine (unless they yielded something like a WaitForSeconds that makes Unity resume them at some other time)
It's not concurrent programming.
Should MoveTowards be in Update or FixedUpdate
It can be in either one. MoveTowards is a general purpose math function that can be used in a variety of contexts
Depends on what you use it for
It's not specific to any.
It simply moves the value of a vector3 towards another vector3.
indeed: it does nothing more
just like Mathf.Lerp does nothing but give you a value between two points
(and Vector3.Lerp!)
I'm moving transform position to move from one position to a target
is there a way to wait till animator finished playing the desired animation?
ui.animator.Play("Attack");
So basically what I have now is that coroutine does not wait till the animation is finished and goes further. And well, yield return new WaitForSeconds() doesn't quite solve the problem since I have different attack animations for different heroes with different duration so it shall be a bit more universal approach.
WaitUntil accepts a method that returns a bool and runs it until the method returns true
That may be useful.
yield return new WaitUntil(() => ui.whatever == 123); will park the coroutine until that function returns true
that's what ChatGPT suggests. Should do the job?
i would advise against using the spam machine to try to learn to make games
If the end of that is || ui.animator.IsIntransition(0), then it will immediately end the loop if the transition takes a non-zero amount of time
it's cut off
oh, I read that backwards
ui.whatever == 123 what do you mean by 123 please?
well, I'd need to see the whole line either way
it was an example of a method
ui.animator.Play("Attack");
while (ui.animator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1f || ui.animator.IsInTransition(0))
{
yield return null;
}
that's what chatgpt suggests
AAAAnd it doesn't get the job done
This would be a decent place to use a https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html. You can have code run when you enter or exit a state in the animator state machine
Pretty sure this would get stuck forever until you enter a state that doesn't loop
yeah that doesn't work like I need it to anyways... will try your approach if I will understand how to do that 😄
You can just check if you're currently in the "Attack" state
That would require fewer moving parts
or use enums to determine what state you are in
MOVE, IDLE, ATTACK
and make your logic based on that
yes, but we have to decide when the attack is over
can do via animation events for instance
yield return new WaitUntil(() => !ui.animator.GetCurrentAnimatorStateInfo(0).IsName("Base.Attack"));
That should be correct. It gets the animator state info for layer 0 and asks if the current state is named "Attack"
ui.animator.Play("Attack");
yield return new WaitUntil(() => !ui.animator.GetCurrentAnimatorStateInfo(0).IsName("Attack"));
asked gpt to implement your approach and it gave me this 🙂 I mean gpt is not useless
I presume that Play immediately changes the active state
ha, well there you go
Although, that's wrong.
It should be Base.Attack
Gpt IS useless, and it's against the #📖┃code-of-conduct to use in questions and answers here
ChatGPT is excellent at producing plausible, yet wrong, code
ow... okay... sorry, I had no idea
It's ok at dialogue at least
Not GREAT but... ok
It mashes words together in a way that looks correct, but isn't
If you want something to happen when an animation ends, put an Animation Event on the last frame of it:
https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
This is the ideal way to do it, yes
Although, it looks like it works fine with just the name. I suppose you need to specify a layer if it's not on the default layer.
if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Jump"))
{
Debug.Log("Jumping");
}
e.g.
from the GetCurrentAnimatorStateInfo page
Is there a Mathf.Approximately for Vectors?
Vector3 comparison already uses some fuzziness
You probably just want Vector3.Distance, though
with some small constant
Vector3.SqrMagnitude(a - b) might work aswell for ya
very small fuzziness, mind you
could probably achieve something with Dot product
rly depends on what do you want to do
Like this?
Vector2.Distance(transform.position, _plantTarget.Value) < 0.1f
Yes.
Gotcha, thanks
== returns true if the distance is less than one hundred thousandth
(which helps deal with tiny math errors)
hey, i get this error on line 18 NullReferenceException: Object reference not set to an instance of an object. Im trying to make something happen when i click but i get this error
void Start()
{
rb = GetComponent<Rigidbody2D>();
GameManager.input.Player.Shoot.performed += Shoot; // <- this is line 18
}
I never compare vectors for equality, since I always want a specific amount of otlerance
Then somerthing on line 18 is null.
How can I rotate the bean of my character controller ??
nothing is null
that's obviously false
becaues you got a NullReferenceException
C# doesn't throw exceptions for fun
i don't believe the CC capsule can rotate
a guy that is 51 messges late
gpt sucks
If you truly believe there is nothing null in there for the object you're looking at, make sure there isn't another instance of the script somewhere
But there IS something null there
can any1 tell me whats wrong its not there
void Shoot is defined and the shoot InputAction is also defined to i dont think that anything is null
in my unity code slot where it should say rigdid body
Okay, so you don't think anything is null
You say what is wrong, we say why is wrong
Now prove it.
Defined? But are they Assigned?
There are a LOT of member accesses on line 18
GameManager.input.Player.Shoot.performed
why is it wrong im following some new turtorial bc im new i got sent it by sm1 and he said this should work
we have literally no idea what the problem is
The fact is, you got an error. There is no question that something IS null there. This is a fact
there should be a section for my ridgid body
You literally have not said what the problem is
You probably have a compile error that's stopping unity from reloading.
so there should be a box for my ridgid body but its not there
Show the console
bet IDE not configured aswell
It's not configured as well, so they should be directed to !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
this?
is this the console?
I watched the video in the tutorial and I still don't get what I'm doing wrong
configure your ide @grand forge
im new so whats that
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
where i type that then
type what?
No? You already shared that
what could be null?
im following a turtorial to try learn the code
type what
you dont type anything
Im so lost
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Literally anything between the dots
The console would be this: https://docs.unity3d.com/Manual/Console.html but you'll need to have a configured IDE first to get help here (part of the server rules #854851968446365696 )
chooes your code editor
and go through each step and configure it
you dont type anything
GameManager, GameManager.input, GameManager.input.Player, or GameManager.input.Player.Shoot
well you havent shown what you're doing yet period, so it's hard to say.
Null Reference Exception errors occur when you're attempting to access a member (in your case field/property) of variable that's null.
Accessing with the dot threw the error because one or more of these are null.
what do you mean what am I doing I'm trying to make each button go to a different 360 photo
you have to show what code is running when you press the button
without you showing that, it's impossible to say.
then add logic that should do it after you click the button
imagine you take your car to the mechanic and say "I'm trying to drive the car"
can the mechanic do anything to help you yet?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TourManager : MonoBehaviour
{
//list of sites
public GameObject[] objSites;
//main menu
public GameObject canvasMainMenu;
//should the camera move
public bool isCameraMove = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(isCameraMove)
{
if(Input.GetKeyDown(KeyCode.Escape))
{
ReturnToMenu();
}
}
}
public void LoadSite(int siteNumber)
{
//show site
objSites[siteNumber].SetActive(true);
//hide menu
canvasMainMenu.SetActive(true);
//enable the camera
isCameraMove = true;
}
public void ReturnToMenu()
{
//show menu
canvasMainMenu.SetActive(true);
//hide sites
for (int i = 0; i < objSites.Length; i++)
{
objSites[1].SetActive(false);
}
//disable the camera
isCameraMove=false;
}
}
Looks like it's based on whatever siteNumber you pass into that function
you'd have to show how your buttons are configured (which is what I've been asking for this whole time and you still haven't provided)
What calls LoadSite
You'd also have to show what you have set up in that objSites array in the inspector as well
hey ive got a problem and i think i know how to fix it i just want someone who knows what they are doing to double check bassicly ive got a ragdol made up of different shapes connected with configurable joints i use its drive force to get it to be animated but an issue i have is when i turn collisions on for the hands gaps appear between the shoulder and arm if i rig the character and have the bones try to link to the model instead will that fix my problem?
is this logical and technically possible?
What is "this"? What are you trying to do?
a canon loader
why is your HealthSystem variable called ballsHeld? Seems like poor name for a HealthSystem variable
i was abt to explain it
yes
holding balls is logical and technically possible
the player needs to take a ball and then load it to the canon manually and then repeat
yes, possible. No your code won't do that.
i didn't want to create an other script for that
make your cannon then make a ball then make an animation of the ball going into the cannon then make a particle effect for the cannon to fire and then clone the cannonball and give it a bodyvelocity in the direction the cannon is aimed and then let it go and when it lands delete it and play an explosion effect
no animation for now just some wait bla bla
You'll get an error if it wasn't a player that triggered this - assuming balls held is only assigned in the first if statement.
canon already ready i just need to change the script
yes
i guess so
idk
Is there a way to get a singleton to call its method when the scene changes? basically i want my save/load system to save then load every scene change
what do you mean what calls LoadSite?
I mean what calls LoadSite
I didn't know what you mean by calls
Hi. One question, does anyone know how can I do like a variable where I can select multiple options please? Like when selecting a layermask, where you can select more than one at the same time
enum with Flags attribute
thanks
Why can I not drag a Prefab that has a Script X on a ScriptableObject that demands a field X?
you can
The arrow doesn't list the prefab
the arrow?
Then you need to learn some of the barest of bare-bones basics of C# because I literally do not know how to explain that any simpler
Even in the Assets tab
Consider the intro to C# guide in the pins
Show the full inspector of this object and the prefab you want to drag in
did you try just dragging in the prefab
that thing barely works sometimes at detecting assets
I can't do that because it automatically closes the tab once I enter the other asset folder
right click it and click Properties
it pops it out into a new window
Right click what?
the script ?
Lock the inspector
The prefab or the scriptable object
or that ^^ lock
Anything you want
this?
if you right click even asset on Asset view
But just for learning: the preview bullseye or whatever cannot display prefabs?
you can pop out its own inspector
how is that a Button?
usually has a hard time for me when looking for a prefab with a certain script
idk if im doing it wrong but never does so I just drag n drop
Mm yes I agree. But thanks :)
this the inspector for button 1
Okay there we go
Do your other buttons have different numbers
this the inspector for button 2
So, no
All of your buttons use the same number
looks good
why doesn't this work.. using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponSpawn : MonoBehaviour
{
public GameObject Weapon;
void OnMouseDown()
{
Weapon.SetActive(true);
Debug.Log("Spawned");
}
}
I have linked the gameobject
void on mousedown???
but it doesn't spawn and the console doesnt write the line either
wrong one here
Okay so it is a different number
void is a return type for a method
Show your objSites array
i think you mean Input.GetKeyDown(keycode(mouse0)
do you have a collider on this object ?
oh nah i dont
cause that function needs collider
yes, button3
what would the difference be with this
not valid syntax lol
how come?
oh ye i writed it bad
there is also mouse built in Input.GetMouseDown(0)
i deleted a duplicate camera and the consoles telling me the script is missing
how can i get rid of that
Remove the component that referenced the missing script
KeyCode.mouse not KeyCode(mouse0)?
valid
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
but different purpose
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponSpawn : MonoBehaviour
{
public GameObject Weapon;
void Update()
{
if (Input.GetKeyDown(keycode(mouse0))
{
Weapon.SetActive(true);
Debug.Log("Spawned");
}
}
}
try this
mouse0 means left click
that'S good
it worked after adding a collider but when should I use the input rather than onmousedown function
That won't compile and also doesn't do the same thing
@visual hedge @clear seal If you're going to just try to guess at the solution at least make it known you don't actually know the answer or you're just going to confuse the matter
do you want to click on something specific to run hat method. or do you want to detect mouse button down In general anywhere to run function ?
so bascicly it act like a raycast touch?
oh... my bad, I haven't seen that that method is called thru button click
okay yeah so is onmousedown really necessary
(sorry for bad english and i never tested that just saw thumbnails)
what is that?
that doesn't answer the question lol
it probably raycasts in the background, so yes it only invokes when the collider you clicked
That's what I'm asking you
I don't know what you put there
show it
thought it was rhetorical, input is the one that can be used anywhere right
what am I showing?
indeed
Correct. The code that other people have provided (once all of the compile errors were fixed) would fire whenever you clicked anywhere. It simply checks if the button is pressed. OnMouseDown checks if you click on this collider
Your objSites array
still dont get the difference cause couldn't both return an output
ohh okay
thanks
so input can't be localized to clicking on a sprite
everything returns an output
void is an output
Input does return an output and its bool or float if you use GetAxis for example
yeah im waffling
I obviously don't knew what that is
Then we're at an impasse here. I can't provide any further help until you tell me what that is
does the intervals of keypress sensitivities on getaxis vary for different keyboards
getaxis is the -1 to 1 one right
okay but do better keyboards have better sensitivity controls?
better sensitivity controls? wdym
that is something you set at the driver or OS level
varies on so many things too
like a keypress from up all the way down would have 1000 different values for a get axis or 100000 for better keyboard
better, no, different key type, yes
The "hardness" of a key press does not provide different values
A key is either pressed or it's not
a half press though
No such thing
no? i sent you a link that explains the difference
yeah i read but couldn't half a press be a 0.5 or -0.5on the getaxis
while on raw it would be 1 or -1
it no no wanna think :(
a half press isn't a thing lol
its either pressed or not
so how does getaxis work
what do you want the code?
You cannot half press a key
off or on
I want to see that array. Where it's defined and where it's populated
i read that
but doesn't that imply that there are values between 0 to 1 and 0 to -1 which would depend on how deep a key is pressed
The sensitivity of the input is defined in the input manager
it ramps up to 1 or -1 based on that sensitivity
but wouldn't that depend on the keyboard
whereas GetAxisRaw does not do any smoothing
No that depends on smoothing settings for that key/axis
how can the sensitivity be calculated digitally
the keyboard has nothing to do with it
You press a key. It goes from not pressed to pressed
It's an interpolation
GetAxis will smooth the value from 0 to 1 over time
entirely in software (in Unity)
GetAxisRaw returns the actual state of the key, no smoothing
oh okay so it goes to 1 if you keep it down till it can reach 1
rather than a tiny press
which would be like 0.2
its mainly meant for Controller sticks/Mouse afaik
The meaning of this value depends on the type of input control, for example with a joystick's horizontal axis a value of 1 means the stick is pushed all the way to the right and a value of -1 means it's all the way to the left; a value of 0 means the joystick is in its neutral position.
keyboard key doesn't behave like that
I guess I'm stuck at the moment
sure if you don't want to share the code requested
They shared the code. They haven't shared the array
ahh misread that as array in code not obj
what is the array ?
I'm currently trying to check if an object is colliding with a different object the moment that it spawns, after searching on internet I can't find any way to do this. Could someone help?
The array in your script. That you coded in and populated somewhere. Show where and what you have populated it with
Physics.Overlap
I mean, it seems to work despite my collider moving?
this?
or this?
oh boy..
it looks like it works, but it will not actually work because moving transform does not respect collision
it will jank on you if you do not do it properly
what do you mean two?
TourManager script
I literally do not know how to explain the concept of the number two
yes
how would i go about stretching and rotating an objects wherever the mouse moves
whats the maths needed or can something easier be done
use transform
rather than some angle calculations
will it make it easy or do i need to use trig
It is more than one and less than three
Half of four
there are plenty of forum posts / unity answers for this
you dont need trig for rotating and stretching and object
so is maths the only way or is there something built in which would stretch and rotate the objects
so... what's the correct way to rotate?
"stretching" would just be setting the transform.scale
"rotate" isn't clear how you want to rotate
: (
2d clockwise/anticlockwise
but if it's easy i probably just need to get good and ill do it when i can
I don't knew anymore
sry for interrupting but what does this button do exactly? does it destroy the object or something else? found out after a few hours that it solves an issue i got when i toggle it off and back on, so id like to access that button by script... (not ideal i know)
My best guess if there's not an inbuilt system, that I'd have to shoot a ray cast to check for any collisions.
It disables the object
you need basic unity functions but you can easily do it without much math
thank u, i should be able to find a way to do that now
if not ill be back
two what?
You literally sent two screenshots with bright red arrows pointing to them
how did you not notice there were two
you labeled them
I don't knew I followed the tutorial
Okay show me where in the tutorial it added the second copy of the script
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 dir = (worldPoint - (Vector2)transform.position).normalized;
transform.right = dir;```
or do you mean rotating it with the mouse axis not position?
idk what a mouse axis is
but the end point of the object would be fixed
and it would rotate around that point
and only it's width would stretch
but i think thats what you mean by the axis#]
ok I looked back I don't see when he did that
How. How can my character go through the loop, but only through one side but doesnt even get half way up when going the other side 💀
yeah but rotating according to what, mouse position, or just moving mouse Left/right up/down indefinitely
mouse position
or the change in the mouse position after clicking down
{
Debug.Log("Updating experience bar: " + currentExperience + " / " + maxExperience);
float targetFillAmount = (float)currentExperience / maxExperience;
experienceBarText.text = $"Level: {level}";
experienceBarSlider.value = Mathf.Lerp(experienceBarSlider.value, targetFillAmount, Time.deltaTime * 50f);
}```
is there a reason my xp bar isnt updating smoothly? am I misunderstanding lerp?
doesn't need to snap to the mouse necessarily
Coroutine would be the cleanest
or use Dotween (very nice for UI animating)
No, still not right. If you press the key with GetAxis, it will go from 0 to 1, but hit each value along the way
If you press the key with GetAxisRaw, it will immediately go from 0 to 1
There is no way to do a "tiny press" nor any way to get it to only go up to .2 (or any value less than 1).
do you prefer dotween or lean tween?
Prime tween
Dotween personally
any reason you like this over dotween, never tried it myself
depends on your RB.
kinematic RB should use MoveRotation.
dynamic RB should only be moved by force.
Alternatively, if you want to teleport, then you need to do a physics query to see if the coast is clear, then change rigidbody.rotation
Why cant I set rigidbody.velocity.x? Do i new to make a new vector2?
that is the only way to exorcise the jank demons from your code
You cannot assign a prop of the struct like that
Looks like you have an unwanted/incorrect collider there somewhere
Is assigning a new vector 2 the only way to go then?
aight, thanks
oh okay so it really is just for controllers
No, I was actually just trying to muddy the waters more haha. It apparantly doesn't allocate, unlike dotween. I dunno if that's worth if by itself.
? No.
It is just a smooth lerp between 0 and 1. It's for keyboards and anything else
I think it's due to the way I apply velocity, I multiply it by the character's rotation in order for the character to always be moving relative to the way their facing; but I'm finding that around 90 degrees along the loop in whichever axis is up is when the effects trigger. On one side of the loop, once you reach 90 degrees; the velocity's seem to reverse to force you back down and on the other side of the loop, seems any forward velocity moves the character to the left.
and its calculated off time
Also thanks.
pressed down
No! Not at all.
lol i dont get it
The instant the key down message is sent. The smooth interpolation begins
Are we still talking about getaxis/raw lol
Yeah looks like interesting features too, gonna give it a try later
https://github.com/KyryloKuzyk/PrimeTween?tab=readme-ov-file#performance-comparison
and the interpolation is based off time pressed down?
I just said no
It takes the same amount of time every time (the time can be changed via settings. But once set, it will take that amount of time). It starts the instant the key pressed event is received
Holding down the key will KEEP the value at one until the key is released, when the key up event is sent, and it will interpolate back down to 0
so the time it takes to return to 0 is compared to the other times you pressed it or something?
It is compared to whatever it is set to
okay yeah
The INSTANT the key up event is received, the process begins
Sure. Or just moving a character so it has inertia
where does this thing get called? i'm looking at LobbyUIMediator.cs from the Boss Room project ... i must have skipped over the Inject stuff when I was learning C#? :I~
should i use internal or public for methods if i want to use methods in different scripts that are on the same gameobject?
Dependency Injection is not something you would learn when just starting. It's a more advanced topic. That looks like zenject I think
:~I ... dang it
Well, internal would make it so they can't be called externally of course... public is what you would use
whether it's on the same gameobject or not is kinda irrelevant here
Does anyone know how to make a ladder work? I dont need animations just need to be able to climb up thanks
How do you WANT it to work? Move forward makes you go up? Or click to climb.
It depends
Inject isn't really something included in the default C#. This code must be using some kind of library or framework that implements it.
Sinple way is to just have a trigger area, if you walk forward make sure it's against the ladder, and increase the y position
Could use raycasts or spherecasts in a similar way, and that would negate the need for checking direction
Okay thank you
ah okay. i wasn't sure if it was relevant or not to being on the same gameobject i think that's what confused me , unless i'm specifically creating assembly definitions internal would function the same way as public in all of my component scripts right?
Would that work even if my player is instantiated into the game after it starts?
Yeah, that would change nothing about this
Unless you spawned inside the trigger area, the event may not send
dont crosspost
Are you using assembly definitions? And do you need them to be separated?
I'm making a vr game and I'm going to implement a flashbanf sort of ability, but you point your hand at another player and if their in range they become flashed
idk how though
no at at the moment. i haven't gotten into a situation where i needed to yet i haven't really looked into them too much
Then stick with public
Easy enough to change when needed.
But yeah, you were right earlier
i know i should learn myself but why doesn't this work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponFire : MonoBehaviour
{
public float X_pullback;
public float Y_pullback;
void OnMouseDown()
{
Vector3 originalPos = Input.mousePosition;
Debug.Log(originalPos);
}
// Update is called once per frame
void Update()
{
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
what "doesn't work" mean
doesn't log the originalpos
input.mouseposition would save the position of the mouse right
OnMouseDown is meant for being clicked on Collider
yeah as i intended
show where you put the script on the gameobject
var targetX = transform.position.x + Random.Range(-2f, 2f);
var targetY = transform.position.y + Random.Range(-2f, 2f);
if (targetX > CameraMovement.MAX_TOP_LEFT.x)
targetX += Random.Range(1f, 4f);
else if (targetX > CameraMovement.MIN_BOTTOM_RIGHT.x)
targetX -= Random.Range(1f, 4f);
if (targetY > CameraMovement.MAX_TOP_LEFT.y)
targetY -= Random.Range(1f, 4f);
else if (targetY > CameraMovement.MIN_BOTTOM_RIGHT.y)
targetY += Random.Range(1f, 4f);
_randomisedBuzzAroundTarget = new Vector2(targetX, targetY);
Is there a logical error? Because the constants are set up correctly, but the target still ignores the bounds
where is the collider.?
cause it sure as hell not where the script it
ohhhh
The component. What object is it on?
It'd log the mouse position relative to screen space - I'm assuming your object is in world space.
yeah it works now 😄
but yeah like Dalphat mentions, Input.mousePosition is only Screen position
not world
big differences
what no..
Screen Position is just the position on the pixel coordinates
World position is where your gameobjects live
Try logging some values like the bounds and the values of x/y.
#💻┃code-beginner message
You see in my example I use this method
so should i just make it a world position thing
ScreenToWorldPoint
thanks
I discovered the Clamp function of Mathf :)
not sure what that means tbh but ill learn what screen-world thing is
screentoworldpoint and worldtoscreenpoint right?
you see the red dot
thats where your mouse is
yh
for 2d would both z's be the same
the function transates that position in relation to the world
so it scales it up to the screen size?
Orthocamera dont have depth so it would be Z of 0
it always keeps the sizes uniform sure if you change screensize it still knows where to put the dot in the world
i dont understand how it is different to the mouse position exactly
other than that it would calculate the depth in a 3d space right
the depth of the object being pointed at
because the mouse doesnt exist in the 3D world
it lives on your screen, hence screen size aka Pixel Size
yeah so for 2d could input.mousposition work fine
or does the screen to world world to screen thing need to be used
Input.mousePosition is Pixel Coordinates
it has no relation to 3D or 2D
The bottom-left of the screen or window is at (0, 0). The top-right of the screen or window is at (Screen.width, Screen.height).
ohh okay so it basically tracks the mouse even outside the window of the game is the issue
nvm i confused myself, yes it tracks the mouse pos
but in my case the object would always be clicked within the window and that's when I want the mouspos saved so it should be fine this time right?
its not an issue, its just that if you want that to translate to the world (inside the engine) you need that helper function
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
or is there another benefit
no because the mousePosition in pixel coordinate isnt much useful to a gameobject (those use WORLD coordinates xyz)
oh okay so if the game were windowed and in one corner of the screen even if i clicked it there it would have a different mousepos than to clicking the object in fullscreen, in the same position
so thats why I should use the world coords?
just make a trigger, when you're inside the trigger "You're on a ladder"
switch up movement to go up instead of forward with WASD
Alright I'll try that
you are overthinking this lol
world-space coordinates are a completely different coordinate space from screen-space coordinates
yeah but is that not how it works?
your mouse would be at the same PIXEL coordinate no matter what resolution
you should use the correct coordinate space because it makes zero sense to work in the wrong coordinate space
if my object is in a windowed version of the game and clicked it would return a diff position than a windowed version in a diff area of the actual screen
if I ask you what time it is and you say "34 feet", that's just plain nonsense
for input.mousepos?
yes thats what its for
yeah
so the thing i was saying about the windowed version giving a diff position would be right or wrong?
if you get what im asking
I kinda don't know what you mean there lol
windowed or not , ScreenSpace is the same place
they're asking about how screen space coordinates change with resolution
they will change, since screen space is measured in pixels
view space coordinates are normalized to the 0..1 range
i am logging the coord when the object is clicked, if i clicked it in one space when it was in full screen then the game is windowed and taking up half the screen - the object would be a diff position on the actual screen, the mouse position logged that time would be different
it would be the same world position but not screen position
so the mous pos returned would be different
Correct.
the ideal thing is to be using the helper functions
okay yeah i get it
but is world - screen better
or is that a helper function
like ScreenToWorld, WorldToScreen etc
viewport right not screen?
Correct.
can i subtract vector3s like this
ofc you can
to subtract the x and y components separately?
you didn't get an erreor, so yes (:
and yeah, it's element-wise subtraction
which is how vector math normally works
* is not defined
just wondering what games have you guys made?
Vector3.Scale is used to do element-wise multiplication
various different shit that are always at 80% completion xD
oh yeah i don't get how scale works i put in a sprite with a certain resolution but then I can't find the resolution according to it's scale anywhere
you got a page i wanna try them out
nah just very old Jam submissions on my itch
can you send that pls
guarded looks cool but doesnt load
Ohh really?...hmm gotta look at the old project and see why
weird cause it works on my PC.. :
must be webgl issue ig
how would i find a child object with a tag at runtime?
if its a child just make a field. why tag?
idk what that means
could you explain?
[SerializeField] private Transform childObject
Okay so i got my ladder to work
you can do also transform.GetChild(indexOfchild) but its not robust
i want to save the x and y values of poschange separately
But if im already moving and i walk into the ladder i dont climb, i have to stop moving and press w while in the trigger
I can send an example if needed
would that work with prefabs?
this is saving local variables
save it ina vector2 ?
ofc
bruh i thought there was just vector3
Unity has Vector2 and Vector3
my game is gonna be fully 2d so should i just use vector 2s
im trying to find a specific instance of a child of a prefab (in this case all my ground blocks will have a tree child gameobject that i only want to set active under certain conditions)
you can use either one
both work exactly the same
yeah it says newpos and originalpos do not exist in the context but I thought local variables could be used anywhere within the code
im not sure how to reference it in script though
no they are local to the scope (the method)
ohh damn
but i heard having alot of public's is bad
yeah but what are you looking for exactly
a script ?
you know, private is a thing
yeah but constricted to one method i don't know how I can do that
do i need to recall the variables when I want to use them?
https://gdl.space/mihitemava.cs this is what i have right now, i put a comment explaining what im trying to do because it is a bit hard to explain it out of context
those are local not private
you declare them OUTSIDE the method, INSIDE the class
is something like this gonna work
and this is the structure of what "xblock" and "zblock" would be
methods do not have accessors for variables inside, since they are all Local and cannot be otherwise
Can someone help please
mm yeah i need to learn the basics
Please do . . .
xBlock is your instance tho
so if they are called outside of all the methods they can be accessed within them all?
yes, but i dont know how to reference the actual tree part of it
like how I initialised the gameobject outside the methods
I meant make a field for the tree with a script on xBlock you access after Instantiate
but GetChild should suffice i suppose
just not solid
if they are Declared outside the method it can be accessed through the whole class yes
if you want you can directly spawn the object As that type too instead of GameObject
SomeScriptBlock xBlock = Instantiate(blockPrefabs[0], new Vector3(j, 0, i), Quaternion.identity);
xBlock.SomeTree // do whatever with it```
blockPrefabs would need to be changed to SomeScriptBlock though
private SomeScriptBlock[] blockPrefabs
I don't think I have an array for the button I have one for the site photos
i dont quite understand the point of that, could you explain why that could be better than what ive done?
no errors so a private called outside all the methods can still be accessed anywhere throughout that script?
well if you're looking for a scrpt called SomeScriptBlock that holds a field for the SomeTree
You avoid a call to GetComponent
as per your code
GameObject xBlock = Instantiate(blockPrefabs[0], new Vector3(j, 0, i), Quaternion.identity);
xBlock.GetComponent<SomeScriptBlock>().SomeTree```
i ended up just putting a script on the blocks themselves like this
is this not good?
that works too lol
actually it wont work if it stars disabled..
scripts dont run on disabled gameobjects
ah i see
i put it on the actual block parent though so it works
gotcha
i tried out my map at 100x100 size and the scene view is laggy 😭
not surprised though
do you have LOD and other optimizations setup ?
no, but i dont think ill have to mess with that for this project, im just testing out what ive got so far
the map will probably be like 20x20 max
My ladder works now thank you for helping @rich adder
yes
oh yeah thank you navarone for helping me as well
Hello, someone can help me?
I'm getting this error, but I don't know how to solve
I tried google, but don't works
FormatException: Input string was not in a correct format.
That's my code
int inGameItemID = int.Parse(EventSystem.current.currentSelectedGameObject.transform.GetChild(0).GetComponent<Text>().text);
I tried to show in a Debug.Log, and the result is always a number
I don't know where is the error :/
But the error are returning this line that I showed
No.
GetComponent<RigidBody2D>().mass;
Thanks
you wont be able to use GetComponent there
so get component is like a function and then the value is called with a dot after
needs to run inside a method
Oh, yeah that's the initializer huh
Do it in Awake
ohh true
And yeah, GetComponent is a method, and exactly what you said. You access properties of that component via dot notation
thats just how the compiler works
Methods are functions that are members of an object (like a class or struct)
these fields are created before methods are
what's wrong with this code
you cannot use something that wasnt created yet
i see the console errors but not sure exactly what
You put public in Awake
btw !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I noticed before it wasnt highlighting red
Make ammoMass a variable in the class, then just assign it in awake
i need it to be public though so should I put it in start() or soemthing
i told you earlier, methods cannot have accessors* they already are local
*aka public, private
oh okay
public float ammoMass
void Awake() {
ammoMass =
}
yeah true lol
anyone know how to stop my projectile from hitting multiple enemies that are stacked on eachother?
Have the projectile remember the first enemy it hits. If it has hit something, don't damage anything else
feels like this should work
errors are x and y_pullback and something about data types being converted
thanks
also it says rigidbody2d could not be found
the referenced gameobject has rb2d
Did you configure your !ide as nav said?
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
config your IDE if you want get help
If you're using VSCode yeah. The devenv is for VS I thought
Which are you using? (Looks like vs code)
no its not right
also this looks like Visual Studio
are you using
or 
blue
ohh
so follow VSCode one
it should not say (internal)
it should show the vscode version
thanks
shows us when its done 🙂
now that it does a debug does it mean its done
the thing still says internal though
yeahh and the lightbulb it works now i think
if it underlines errors then its working, try typing something see what appears
no it doesn't do that
i need to find the file they are asking for
also quick question can you run a build if there are errors
a file ?
yeah cause it still says internal
yeah
the fix is there, follow the steps exactly
okay
yeah im not sure it doesn't work still
it says something about restricted mode which limits the extensions so i take it off but they still don't work
it would not launch it in restricted mode
you did not configure it correctly im certain
In C# I can use return to exit a method, but if the method uses IEnumerator, how do I do that? yield return null seems to skip the frame so to speak
yield break;
Thank you
How do I scale the UI to fit all screens?
check the documentation pinned in #📲┃ui-ux to learn how to anchor and scale your canvas elements
where in the documentation is that?
i think it's cause it says internal
where is that?
where is the specific doc
where it tells you that
holy shit, it says internal because you did not configure it correctly, what dont you get lol
The layout link
ty
ik im just checking on yt
when its configured correctly ^^
yeah
So, do you have the Unity extension?
The Visual Studio Editor package in unity (at least version 2.0.20)?
Is there any error in the editor about an SDK?
cause i followed the page but it doesn't work
"it doesn't work"
yes 2.0.23
Ok, and the other two things?
no error about sdk
have unity extension
although i just installed it
so maybe i should restart unity?
Install the unity extension, install the package , in unity select vscode . regen project files in external tools
