Hi again! Thanks for the help earlier. So I tried using slerp, but I'm still getting the same problem of the rotation applying on its own axis. So for example, when it rotates 90deg on X axis, I later want to apply a 90 rotation on the Z axis, but it will apply Z axis locally which is Y in world axis.. Why can't I wrap my head around a good solution here..
#π»βcode-beginner
1 messages Β· Page 142 of 1
whats the best way to spin a disk based on cursor position
That could mean a bunch of different things. How is it going to work, mechanically?
It's not essentially any different from any 2d/topdown "aim-at-cursor" implementation I would think
So, if camGunner does not exist and you press C, you want to enable camGunner? That doesn't make much sense
I don't know how to check if it is active
Feel like I should know this but I'm a bit rusty. I currently have a Game Object with a Canvas as a child and a Text (TMP) as a child of the Canvas.
I am trying to instantiate the object and change the text. I currently have
GamObject NewDot = Instantiate(Dots, new Vector3(Random.Range(-10, 10), Random.Range(-5, 5)), Quaternion.identity);
NewDot.GetComponentInChildren<TextMeshPro>().text = i.ToString();
but it keeps returning " reference not set to an instance of an object" for the 2nd line.
Any tips?
Then it would seem that NewDot doesn't have a TextMeshPro component on it or any of its children.
Considering you said it was a canvas, you probably want to get a UI TextMeshProUGUI instead of a world-space TextMeshPro (or just use their shared parent type, TMP_Text)
<TMP_Text>
yep that was it
thanks both
its been too long since I did Unity stuff. more used to the old fashioned Text fields
Hi guys, I'm having issues using unity 2017.4: finding text mesh Pro: how can i fix This?
bit late to the game, for 2017 TMP was an asset now it's a package
what version of unity do i install for windows 7 that has TextMash Pro?
win 7 32 bit, none, win 7 64 bit, docs say anything up to 2021, whether it works or not is another question
Does anyone know how I would go around clamping the camera to 90 degrees?
PlayerCamera.transform.Rotate(-MouseDelta.y * Sens,0,0);
don't use transform.Rotate if you want to clamp the rotation. instead keep track of the current desired rotation in a float variable that you add to when you have mouse input. then you clamp that and assign it as the rotation using Quaternion.Euler or something
if you search "clamp camera" in this discord you'll find plenty of examples of how to do that
also obligatory: use cinemachine. it already has clamping built in
I implemented a pickup and a drop system for my FPS game, but if I drop a 'pistol' for example, it starts flying in the Y axis upwards. It has a rigidbody, and I'm just enabling gravity when dropping and adding some force relative to the player's forward vector. Why can it be? Also other objects dont do this, they work just fine.
if you don't enable gravity what happens?
Probably colliding with itself or a child object
// Mouse & Camera Movement
Cursor.lockState = CursorLockMode.Locked;
DesiredRotationX += Input.GetAxis("Mouse X") * Sens;
DesiredRotationY += Input.GetAxis("Mouse Y") * Sens;
var ClampedRotationY = Mathf.Clamp(DesiredRotationY,-90f,90f);
transform.rotation = Quaternion.Euler(0f,DesiredRotationX,0f);
PlayerCamera.transform.rotation = Quaternion.Euler(-ClampedRotationY,0f,0f);
My Player is rotating correctly on the X axis but my camera doesn't move with the player
On the rotation
it keeps looking in the same direction
you've put the script on the wrong object and/or assigned the wrong object to the PlayerCamera reference OR your hierarchy is set up incorrectly
Yeah but the Y rotation is working correctly
Yep ^
show how the hiearchy is set up
and the inspector of the script (and which object the script is on)
PlayerCamera.transform.rotation should be PlayerCamera.transform.localRotation
That works
Thanks
The object stands still, but the force never gets applied and the drop doesnt happen
Well child objects only have mesh renderers, how can it collide with itself?
how can i delete a tile in a tilemap in code
Good night everyone... I have one little question related to boxhelps... and if someone could help me i'll really appreciate it: How do I make Right BoxHelp automatically adjust vertically to the size of Left BoxHelp in real time in this case? so that in height the right always measures the same as the left. This is the both boxhelps code https://paste.ofcode.org/rHEZVn9pNbh8KGBgFxnKjB
why does this happen?
wym doesnt exist
an object has three children
i ask for the fourth child
the fourth child does not exist
well, yes, the if (chance == 1) block doesn't try to get any children
yes, I would expect the first block to work just fine
then how can i instantiate children of a gameobject seperately?
it also seems very weird to get child transforms of a prefab and instantiate those individually
im dumb
why does it seem weird
why would you need to? your pipes are always the same distance apart from each other. just instantiate the parent object at your desired position and the children will be positioned relative to that
especially since there is probably important logic on the root object of the prefab
i want the pipes to be touching
just move them after instantiating the prefab
nope
you can do that?
but theyre children
but you've already demonstrated you know how to get the children of a transform
just do that on the instance
your code completely loses the MiddleTrigger object
what even is transform lol
that seems like a problem to me
which you aren't instantiating...
every game object has a Transform component on it. the Transform tells you where an object is, how it's rotated, and what size it is
along with what objects are children of it and who its parent is
bump, still need help with this if anyone knows what's wrong T T
Been trying to find workarounds for the past few hours to no avail and it's burning me out now looool
well, first, you can't do transform.GetChild because transform is the Transform component on whatever object this component is attached to
your Pipe Spawner component or whatever this is
but you said
oh, not the prefab
correct
mb
it's your transform
what is the type of pipe?
alr ill be back
and thatd instantiate it?
ur getting it on that second line but ur not calling any functions
Transform pipeTop = instance.transform.GetChild(0)
dont u need to do this
and then modify pipeTop
You haven't actually said what you want to do with it yet
So that part is left up to you
okay but again, why do you need to change the positions of the pipes individually? just change the position of the parent object
in fact you can just tell the parent object to spawn at a specific position
what do you mean you want them to be touching?
and you can't do that in the prefab why?
how do you get through that then
youll shoot through and break it
not sure how ill implement that yet
its supposed to blow a hole thru
i gotta figure out how to do it
trying to delete an instantiated object after a while using this but it doesnt work
i even tried destroy(instance)
what does "doesn't work" mean?
the object isnt deleted
no errors in your console?
nope
what is that code destroying?
no, it's destroying gameObject
what is it meant to destroy?
gameObject is whatever object your component is attached to
what class is this screenshot a part of?
u mean script?
instance would be the newly instantiated object. which of course won't be in the deadzone right after being instantiated π
exactly thats why i throw it into the abyss
it might be something like public class Foo : MonoBehaviour { ...
i changed it to instance
gameobject like u said destroys the component connected
so it shouldnt work
this will still only check if the instance is out of bounds once
the moment you fire the arrow
ohhh
Perhaps the arrow should have a component on it that checks if it's out of bounds
yes
thats probably what i shud have done
works, beautiful
i need to start using my brain
this is where you learn to debug.log
when you have a long chain of dot operators going on, you want to check if each and everyone of them is null, ideally start with the last element
https://unity.huh.how/runtime-exceptions/nullreferenceexception
at a guess i'd say the collider you hit doesn't have a parent
actually you debug from the start because it'll still throw a exception with logging if the null is earlier
one or another lol
Im having an issue where it still executes the bottom code even if it touches the player, how can i fix this?
the first if statement should stop that
Not possible unless the player doesn't have the playerscript
Add debug.log
Print the object you're hitting
does an audiosource play its assigned clip when it starts up?
If play on awake is enabled
thats probably it thne
why dosent the dash work https://paste.mod.gg/natwraudpsky/0
A tool for sharing your source code with the world!
you overwrite the velocity in Update
thx
https://paste.mod.gg/qjxfjwnjzftc/0
Someone help me fix this, the issue is explained at the top
A tool for sharing your source code with the world!
your raycast has nothing to do with opening doors. your keypad will open a door whenever E is pressed
if you remove that code from the keypad's update method and instead check for input when your raycast hits something in your PlayerInteract component it will do what you expect it to
can you teach me how to do the last part?
i just explained how
check for input in your PlayerInteract component. not in the Keypad component
you do know i have no idea what you've just tried because i cannot see your code in your code editor, right?
but you're probably calling Interact on your PlayerInteract object instead of on the Interactable component you get with that convenient GetComponent call you have (though that should probably be a TryGetComponent call since you null check it immediately anyway)
also if the error is not underlined in red in your !IDE then it needs to be configured π
π‘ IDE Configuration
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
if i do audiosource.play, then while its playing i change the clip and play the new clip does it stop the old clip
so, ive placed the check for input here, and when i click e on the keypad nothing happens
why would you put it there
Also, I don't see anything underlined in red, did you fix the error or is your IDE not configured?
it doesnt underline anything in red ever β οΈ
Configure your IDE π
wrong thing, i repasted it there accidentally
so i meant, i pasted it here:
and it returns with this after i paste it
configure your ide. it is a requirement to get help with your code here
that wouldn't prevent a project from opening. it's just an editor issue
done,
error:
Look at your braces and indents, it's a mess
2nd day coding bro π
also is that not you checking input in that last if statement to call the BaseInteract method?
or did you not write this code so have no idea what it actually is?
time to do it proper then
i wrote it, just followed a tutorial, i know what some of it does, my intent was to have the interact in the raycast script so that it would verify under the hitinfo
yes you already have that. that's what that last if statement is supposed to be doing
i moved the getkeydown check to the Interactable.cs file, and when I did it removed the error, but just doesn't work
okay you clearly have no clue what your code is actually doing. i suggest you start by learning the basics instead of blindly copying random tutorials
where or from who would you reccomend i start learning?
there are beginner c# courses pinned in this channel and the pathways on the unity !learn site are a good place to learn how to use the unity engine
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
do I learn using the C# courses first or learn how to use the engine itself with !learn?
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
c# first imo, but it's up to you
Idk in which channel to talk about this, but when i try to install VSC ide the unity asset do not appears, and it seems like there's no place where i can download it
!vscode π
Am already on that page and i still dont find where to install the asset
what asset
Visual studio editor in the package manager
well have you looked in the package manager to see if it is already installed? because unless you've uninstalled that manually then it should already be there
Oh, am sorry. I din't check the unity registry
do i read the documentation then or just follow the courses?
ya not getting far without knowing your c#
surely you can figure that out on your own?
I know this may be a very begginer question, but someone can pass me a tutorial in the DM about how to alternate a bool between different scripts? Basically i want to make that in the start you dont have a gun, but when i pick up the object i want to make the bool of the script that checks if the gun has been picked true
Well, you need a way to get a reference to the gun, so youll need a method to pickup on your player. The item itself can have a collider such that you'll cast in the area when you call your pickup method.
I kinda dint understand (i dont natively speak english)
Probably best to lookup a tutorial on youtube as you're dealing with quite a few concepts here.
I search something like:How to change variables between scripts in unity?
Well, you need the reference to the item first which is the bulk of the code.
welp i just found a 1 min tutorial that helped me, ty tho
GameObject smokespawnedin = Instantiate(SmokePrefab);
DontDestroyOnLoad(smokespawnedin);
Smoke = smokespawnedin.GetComponent<ParticleSystem>();
why doesnt this work it spawns in and is added to the dontdestroyonload but smoke doesnt get set to the particle system
Maybe there's no particle system on the prefab
there is
BTW why not just use ParticleSystem As the prefab reference type then you won't need GetComponent
didnt know you could do that
Maybe this isn't what's assigned to that reference
how would i do that
public ParticleSystem prefab;
void Spawn() {
ParticleSystem instance= Instantiate(prefab);
}```
Exactly as you'd expect
Also a DDOL particle system is... Odd
its a really weird way of doing stuff that im doing
but it works
hopefully
Why though
because basically the player and the ps need to be seperate but when the player moves through scenes it needs to follow
its a smoke screen ability the player has
Really, the player (and managers) should be in a root scene and all your other scenes are loaded aysnchronously.
That way you don't have to deal with DDOL's, since it's always the same object.
This happens when i trigger an object that is supossed to dissapear when i pick it
But it only appears when the starting voice is sounding, otherwise it will not even trigger any of the debug logs
The object you're destroying has the camera on it? π€·ββοΈ
Nope
Seems self-evident that you are
Where's the camera in your first screenshot?
thats a cursed == true at the end of that statement
why not actually print useful logs, with the object name and passing it to the context parameter
Also, your code seems very under-highlighted, which would indicate that your IDE may not be completely configured
I have passed the entire day configurating it without it working
And also ... where is the camera in your first screenshot π€
It's on the bean (the player)
Where in your first screenshot is the "bean"?
Well, you definitely need to revisit the configuration steps and make sure it does work, because programming without a properly configured IDE is a waste of time. !ide
π‘ IDE Configuration
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
am sorry, am stupid
Already did all the steps and it stills not working, all i unlocked was a light bulb and nothing else
You am is not are π€
What?
Did you install C# library with Visual Studio installer? Might come with Unity debug tools if you chose that option
I use VSC
Oh i had to?
If you only just got Unity and just started trying to code VSC with C#, you might just need to restart
Well, am goin gto
Ok
I used VS in my old computer, and somehow it got configured automatically or smth
Were you coding with C# back then?
yep
I fixed my dumb mistake, but the thing is, the trigger only works when the audio is sounding, not when the game is chill
C# dev kit extension should install an sdk, and you either need to restart or manually add it to your computers PATH variables for it to work
Edit: Fixed below
I am taking basic tutorials in c# for Unity. All iwant to do is add a vertical offset of 1 to the instantiated prefab.
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
}
this is launched from the position of a Farmer character that moves left and right. if i do this:
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(projectilePrefab, transform.position = transform.position + new Vector3(0,1,0), projectilePrefab.transform.rotation);
}
it moves the Farmer up 1 every time i press space, too. the goal is to have the instantiated Carrot at a height of 1, always
Ok, i should not have added the second transform.position after the equals.
This seems to work
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(projectilePrefab, transform.position + new Vector3(0,1,0), projectilePrefab.transform.rotation);
}
This line: cs transform.position = transform.position + new Vector3(0,1,0)
Will move your original transform up every time because you have an assignment =
Thanks
You probably just want transform.position + new Vector3(0,1,0)
Done, in the message above your response. π
Ah
Okay so I have been trying to figure something out for over an hour
I am trying to make something like a computer, where when you hit a button a tab opens, and when you hit that again a tab closes
I have it so that it can detect when you hit the button, and even do so much as make it appear or dissapear when holding down on it
But I cannot for the life of me figure out how to make it toggle
`using UnityEngine;
using System.Collections;
public class Hide : MonoBehaviour
{
public GameObject Square;
public GameObject App;
void Update()
{
if (Input.GetMouseButton(0))
{
Square.SetActive(false);
}
if (Input.GetMouseButtonUp(0))
{
Square.SetActive(true);
}
}
}`
that is my code
I have another code for another thing
instead of using GetMouseButtonUp/Down keep a bool that determines what state it should be in, flip the bool each time the button is pressed (but not when released) and pass that bool to SetActive
i mean, that is how you declare a boolean variable, yes. i don't know what you are expecting that to demonstrate here though
im not super familiar with bool
there are beginner c# courses pinned in this channel. you should start there
Okay thank you!
wait so I would set it like that to start, and then whenever I input it flips it?
give it whatever state the tab should be in. true == on. false == off
alright
if (Input.GetMouseButtonDown(0))
Square.SetActive(!Square.activeSelf);```
`using UnityEngine;
using System.Collections;
public class Hide : MonoBehaviour
{
public GameObject Square;
public GameObject App;
public bool onOrOff;
void Start()
{
onOrOff = false;
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
onOrOff = !onOrOff;
}
if(onOrOff == true)
{
Square.SetActive(true);
}
else
{
Square.SetActive(false);
}
}
}`
okay so
I got it to work
thank god
please go learn the basics of c#
but it happens when I click anywhere on the screen and I wanted it in just a square
okay
What is the point of that bool
which
if(onOrOff == true)
{
Square.SetActive(true);
}
else
{
Square.SetActive(false);
}
this is honestly painful to see. you know you don't have to check the current status of the bool, just pass it right into SetActive
Just toggle the object inside the input if statement
ah
well i mean
it works
listen okay I know I don't really know how to program but I'm just trying to get through this part before I dedicate a ton of time into learning
I have no idea how to get this to only work when hitting a specific square though is my main issue
isnt raycasting a beam though?
If my object is a square then how does that work with raycasting
The beam hits the square and detects it
So your code knows which square to toggle
BTW if you deactivate it, it won't be possible to Raycast it anymore
You should only disable the renderer or something
how would I go about disabling the rendering?
Disabling the whole thing was all I could find on google
As with most components you get a reference to it and do .enabled = false on it
If these are 2D squares you can use https://docs.unity3d.com/ScriptReference/Physics2D.GetRayIntersection.html
Assuming they have 2d colliders
thank you!!
why can't i click my button?
#π²βui-ux
but also you don't seem to have an EventSystem in the scene
i don't know if im in the correct channel
so i added a new FPS controller and im kinda having some issues with gravity i was trying to find tutorials but it dosen't work for me and i only added public float gravity
CharacterController does not apply gravity automatically unless you use SimpleMove. but if you use that you cannot jump
also !code
Posting 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.
i don't need jumping system
eventsystem doesn't change anything
well at the very least it is required to get input for the Button component and other UI stuff
one question what does this do?
it's how you share code correctly
you read what the bot told you to do and share it that way
Hi, I have a 2D game and I'm trying to rotate my player whenever it moves in a direction. I'm simply setting transform.up to the moveDir like this:
transform.up = normalizedMoveDir;
However I notice that when the move direction is directly downwards, it changes the X rotation of the player instead of the Z rotation. In every other case it changes the Z rotation correctly. But when I move directly downwards it changes the X rotation. Any idea why this is happening?
instead of assigning transform.up you could get the desired angle for the Z axis and just set the rotation using Quaterion.Euler instead. it's probably flipping around the X axis because it's the quickest way to get to the desired rotation or something equally as simple as that
ah ok, so setting transform.up is not reliable?
well you see what a possiblity of assigning it does. it's not that it isn't reliable, it's that it really only cares about pointing the Y axis in that direction. it doesn't care about the X or Z axis
I see, got it, thanks!
how to use Invoke? Invoke(nameof(StopSelf), flightDuration); right? what difference between nameof(MethodName) and "MethodName"?
garbage?
if you were to change the name of the method without using the refactoring tools it would give a compile time error instead of a runtime error. it's just generally better to use nameof when you want to use the name of some method or variable instead of hardcoding the string
but it generates same amount of garbage?
pretty sure they are both interned at compile time so yeah, i guess you could say its the same amount of garbage
thanks! so, if i want to reduce garbage collector calls to minimum, i should go with tons of "if" in Update instead of Invoke?
i mean, it's not related to garbage collecting the strings. invoke uses reflection which is where its performance impact comes from
i hope i understand this)
Hello! Does Unity support C++?
you can write plugin in cpp
Ah, so I can't write anything other than plugins via CPP.
correct. C++ is used for native plugins, and C# is used for regular scripting of your objects
Ah.
Do you guys think it's worth it to learn C#?
Or should I just move to another engine that utilizes CPP like UE.
do you want to use unity?
if yes, then you'll want to learn c#
if no, then why are you here but also it depends on what you do want to use
I simply want to create, indie games, Unity seems like the best option.
Are there any good C# Unity tuts?
I have a strong understanding of CPP, not sure if that changes anything. π
there are beginner c# courses pinned in this channel. and the pathways on the unity !learn site are a good place to start learning the engine
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
hi, just wondering why is it that both characterSkills and CharacterSkillsList have been cleared when I only called .Remove for characterSkills?
GetRandomSkills() was called 3x in a coroutine.
lists are reference types. that first line in the method makes them the same list
they are the same thing
you can copy a list by passing it into the List<T> constructor or calling ToList on it
would have been a disaster, glad i've asked here
What's the big difference between C# and CPP? π€
Thank you so much!!
thanks also!!
cpp class and struct are the same but not c#, completely different things
There are a lot of big differences.
i was just thinking about this. if i make some variables on PlayerController, it makes sense to me to have them private and make getters and setters for them, but in this particular example, Rigidbody2D and Rigidbody2D.velocity are already accessible anywhere. i can still make a getter/setter for the velocity of the rigidbody attached to the player, but is that really the right approach?
We do it like this yes
Otherwise you need to get the rigidbody over and over again and chances are you are also getting the player controller as well
or maybe done like a other.GetComponent<PlayerController>().SetVelocity(testVelocity); , and inside PlayerController, private Vector2 playerVelocity; and public SetVelocity(Vector2 velocity) { GetComponent<Rigidbody2D>().velocity = velocity;}
Well dont get the component in the Set method. Get it once in Start for example and cache it to a variable
okay sure
but i mean like, should i have PlayerController itself have a private velocity variable
Not needed you can set it directly to its private rigidbody variable
with getters and setters for that, and the setter operates on the velocity of the attached rigidbody2d component within PlayerController?
so PlayerController has a private Rigidbody2D rb;, rb = GetComponent<Rigidbody2d>(); inside Start(), and then a public SetVelocity(Vector2 velocity) { rb.velocity = velocity; }
is that the general approach i should be taking
Again it depends this will set the velocity directly overwriting any AddForce that happened before it
well yes, but just as an example
if i want an object on the scene to set the velocity of a player that touches it or smth
basically if i want a gameobject external to the player to modify the player's velocity, then PlayerController should have a private Rigidbody2D variable that is cached with GetComponent in Start(), with some public methods that other classes can use to modify the player's velocity?
Again Im just making sure you understand what setting the velocity directly does. For example in our boomer shooter we have a AddExternalVelocity method on the CharController that ADS to the current player velocity. This way a jump pad adds vertical velocity while preserving player momentum. As a rule we never set velocity directly we only add
yes i am aware of that, but what i'm clarifying rn is have a private rb2d on the player and have some public methods that operate that instead, right?
Well technically the player is always falling onto the jumppad and we wanted a trampoline effect so what the jump pad does is it takes the current player velocity inverts the y adds its force too it and set the new external velocity. The whole system is a bit more complicated than this but this is the main idea
okay sounds good. i'll work on refactoring some of my stuff
on that note though, i get that adding velocity will preserve existing momentum and stuff, but how did you solve the problem of your player having a negative vertical initial velocity when they hit the jump pad?
ie they jump/fall onto it. if you're simply adding a velocity, then running into it will produce a different height than falling onto it
oh okay. doesn't seem applicable to my use case but that's pretty cool. gonna try playing with dot products of the player's velocity and the transform.up of the jump pad
thank you for your help
I implemented a pickup and a drop system for my FPS game, but if I drop a 'pistol' for example, it starts flying in the Y axis upwards. It has a rigidbody, and I'm just enabling gravity when dropping and adding some force relative to the player's forward vector. Why can it be? Also other objects dont do this, they work just fine.
The rigidbody's velocity's changing constantly
this code probably doesnt relate to the issue then, if it works for all other objects. Check your pistol specifically, maybe its colliders are constantly colliding/trying to depentrate thus moving up. Maybe your have another script which just moves it up and forgot
it was the animator's fault, I just disabled it when dropping
how can I change the background color of the text button in the unity
the background color is driven by the image iirc
Can someone help, I don't know why my Roslyn is eating up so much memory? I've only begun my project a few days ago.
Maybe expand on the details
What is this namespace, sorry
π
both
i mean in unity too
Make sure the package is installed via the Package Manager
it is
Unity says otherwise, it seems
ill try restarting unity
Are you sure it's not UnityEngine.Pathfinding instead of just Pathfinding by itself?
i treid them, doesnt work
Em check using UnityEngine.AI or smth with UnityEngine namespace maybe? Cause all unity namespaces are in UnityEngine namespace usually
not all, TMPro doesnt require UnityEngine.
You are probably right, but check UnityEngine.AI namespace
doesnt help too
i tried
Okay
Or you can check the docs, it will display which namespace the types are in.
Or you could make a variable of a type, and use the VS Quick Actions to complete the namespace for you
Type your wanted code and auto import
In addition you can go to packages folder and check out some files there
NavMesh should be in the Unity AI namespace https://docs.unity3d.com/ScriptReference/AI.NavMesh.html
I check docs and everything else, it just doesnt want to usePathfinding
Unity.AI.Navigation
That doesn't seem to be a thing. Comment that line out.
Now use the quick actions to import the namespace
It's the light bulb icon that appears when you hover over an error with your mouse
Looks similar to your problem
i have the same script on 2 object how can i make them work separately?
They are separate - assuming different instances of the same component script.
What do you mean, can you explain in more details with code example?
what icon?
idk what you mean
The light bulb icon
oh i see
it says that i can add System.IO to using but when i do it i get more errors cuz its NavMesh path
Yep so it's not detecting that the package is installed
Restart VS and try the same thing again
Then close VS, go to Edit > Preferences > External Tools, and click the Regenerate Project Files button. Then open VS again
Where did you get this code from? Are you certain it wasn't supposed to be https://docs.unity3d.com/ScriptReference/AI.NavMeshPath.html?
Wherever you got it from, make sure to copy all steps exactly as they've done.
Well, i got it from some guy, and this it not my game
Hey, do any if you know a good tutorial to sart scripting and actually understand what youβre doing?
depends on what you want to do
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yeah this one is good one too, but i did only 3 lessons end went to youtube
Just get started, cause I did a game by watching some tutorials on what I wanted to implement but I didnβt understand what I was doing
Thx
same
but i just continued learning and now i mostly code with no tutorials
Like the only thing I coded mostly myself is a button to switch scenes
how do i remove a game object from an array
Arrays are fixed size, so you technically can't remove an element.
Prefer using a List<GameObject> if you need to dynamically add and remove items
Or set it to null
okay thanks
But that brings other problems
So, I am setting my game state based on Axis input from idle to running, which works; however, if I immediately switch the cursor key from holding right to left, my character slides over the floor with its first frame rather than utilizing the running animation
is this some limbo state that I enter into that does not properly run animator?
Have your Animator window open while playing so you can see what transitions etc. are happening in real time
I suspect it has to do with this:
"If youβre using Input.GetAxis it will return 0 when both are pressed."
(reading something on Reddit)
spriteRenderer.flipX = false;
state = MovementState.running;
} else if (dirX < 0) {
spriteRenderer.flipX = true;
state = MovementState.running;
}```
Hey, this might be a stupid question. Which axes does Rigidbody.angularVelocity use?
Is it world or local axes
Ahhh, interruption sources, interesting
I have a scriptable object and I'm trying to pass a generic script into it but its not letting me add anything? Any ideas why?
What exactly are you trying to add to it?
Just a script that plays additional functions etc
Wdym a script?
What precisely are you dragging
The script itself?
yes, for each scriptable object I have a script that I'm trying to add into the scriptable object.
You don't drag scripts into such slots
You drag GameObjects with that script attached to them OR if it's a ScriptableObject then an asset of that type
What exactly is SkillBase?
MonoBehaviour?
ScriptableObject?
Skillbase is monobehaviour
Then you'd need to drag a GameObject with one attached to it into that slot. Also since this is an asset itself, only a prefab would fit there
Assets cannot reference objects from scenes in the editor
mmm okay, im not referencing anything in the scene anyway. But does that mean I have to basically create 3 objects for each skill?
Sounds cumbersome, I'm only doing this because I cannot access monobehaviour within a scriptable object. Is there another workaround?
I don't really understand why SkillBase is a MonoBehaviour
i figured cuz a scriptable object doesn't inherit monobehaviour so
I'd be locked out on creating certain functions
So? But why does it need to be a MonoBehaviour in the first place
umm i dont really have a concrete reason why, but isn't there some limitations because it doesn't inherit monobehaviour
like lets say instantiation, or whatnot. Anything that would be in a normal unity script
Instantiate has nothing to do with MonoBehaviour
It's a static method in UnityEngine.Object
You can call it from anywhere
Hello there! Does anyone know any resources to do something similar to this in unity? Where the game scales up or down dynamically depending on the window and not using a fixed resolution?
You mean the UI scaling?
you can use the Canvas Scaler component
the actual world already scales depending on the window height
#π²βui-ux question not code
Not UI. The game itself.
The game itself always scales according to screen resolution
You don't have to do anything special
i meant the game itself in the background, i probably shouldnt have pressed pause in the game
really? weird because it looks fine in the game window but when i made a build half the screen was basically cut out
Wdym by half the screen cut out? You sure you're not talking about UI?
I think? Maybe I am. Unsure now. I will move to ui just in case lol
alright ty
if(victimPiece == "Knight" && attackerColor == thisColor){
curCount++;
}
}```
Identifier expected
did i screw up with syntax or something else?
Hi guys. I know physics things should go into FixedUpdate but I'm not sure where just adding fixed velocity should go also in fixedupdate?
myRb.velocity = moveVector.normalized * moveSpeed;
Yes, also in FixedUpdate technically but you can get away with that in Update
Do you also have a why for me just to wrap my head around this? π
What do you think velocity does?
setting a constant speed into x direction
It doesn't do anything until the physics simulation runs
When the physics simulation runs it moves the object
FixedUpdate runs at the same cadence as the physics simulation
ah okay that makes sense yeah, just setting it on its own does nothing
So by setting it during FixedUpdate that's the appropriate time to make changes to it right before it gets used by the simulation
hence why i can also put it in udpate but best practice would be to put it still in fixedupdate?
Yes
ok thank you very much π
Would it be more efficent to instantiate prefabs with a Vector3 offset or a "Spawn Point" gameobject? Or does it not matter?
you're definitely prematurely optimizing
Ok, thanks
Is it possible to have an image/object show up a fixed position on the screen
such as a health bar ect, im confused about how to achieve this
easier to do with UI
wdym Ui
@upbeat stirrup actually i dont think thats premature. a spawn point gameobject would require you to have an extra gameobject in your scene, depending on how many you have it may start affecting performance since gameobjects have a performance overhead. and if it becomes a problem later then fixing this would waste a lot of time (manually going through every single one of these prefabs, removing the spawn point gameobject and assigning a offset instead)
Alr, thanks alot!
quick question
i am trying to have it so that if you are holding left shift and press a move it does the reverse
if (Input.GetKeyDown(KeyCode.U) && !isRotating) MakeMove("U");
if (Input.GetKeyDown(KeyCode.U) && Input.GetKeyDown(KeyCode.LeftShift) && !isRotating) MakeMove("rU");
it doesnt appear to be working
It's pretty unlikely you'll be hitting both U and Shift down in the very same time frame (of 16 milliseconds at 60 FPS)
You should use GetKey for the Shift key
does that mean if im holding it down
Yes
cool let me try it
Wtf images don't seem to load on my side, anyone else?
images wont send for me
Yeah I've seen the Discord Status page, they're aware of it
since when is discord down like that?
yes, I guess you'll have to use e.g. imgur
think its back
For some reason, i cant move a text mesh pro which is the child of an image, into the text mesh pro public field of a script attached to the image, why is this?
Is there a way to destroy an item's parent?
yes
Destroy(transform.parent.gameObject);
As in when you latch on to the bottom part of the vine (where the collider is), and after a few seconds, the whole vine itself disappears
Destroy(transform.parent) or Destroy(transform.root) if there multiple levels in the heirarchy
because types dont match or ur putting scene object into prefab
prob the former
I'll try that
it should def match
prove it
Guys, i have a cube that is supposed to represent a coin (with a trigger), the thing is. When you start the game a audio sounds, but when you touch the block after the audio sounds nothing happens, i even have a debug log and the log dont even works, the trigger only works when the voice is sounding, anyone could help?
why would audio at all have control over trigger
unless you specified so somehow..
check console for errors
idk i just placed it as a audio that sounds at awake
there are no errors
it looks like this
when the audio is over
basically u can noclip the cube without it dissapearing
the code makes it to destroy when u enter on trigger
show code
types dont match
So whenever this object collides with anything you destroy whatever object thing is
you're trying to drag a textmeshpro ui into textmesh pro
change type to TMP_Text
thing is a variable (GameObject) that it's the same cube that enters on trigger
It is not. It's a TextMeshProUGUI. They have a shared parent type of TMP_Text if you want to use either
Show full !code
Posting 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.
Okay, so, where are you assigning thing
whats on line 64
In the same cube
Then something on that line is null but you're trying to use it anyway
This object has no parent
then transform does not have a parent
Okay, so whenever this object collides with anythinf, delete the cube you've dragged in. Do you ever get your debug log
I thought it does
I'm trying to destroy the entire 'quickvine parent'. Section 6 is where my character swings from, and has the collider
I only get it when the audio is sounding
which object has the script
My Third Person Controller
Audio has nothing to do with this
so how would it destroy this..
The collider is attached to the Section 6
Does that have a parent
No
idk why but when the audio ends the trigger dont works
Then why are you trying to destroy it
log dont even appears
Show your audio code
then collision isn't happening
there's no audio code, it's just a gameobject that has a audio that plays on awake
Because of a game mechanic I came up with. I'm adding vines to the game where you only have a second to swing off of them before they disappear and you fall
Then it 100% is not affecting any of this
But then why the ontriggerenter dont works when the audio is over?
get the reference to the correct vine when you swing on it then
No I mean why are you trying to destroy the parent of your third person controller when it does t have one
I'm not trying to
I'm trying to destroy the parent to the section I'm holding on to, i.e. the vine itself
My guess is because you have code that destroys something when the audio ends and you're destroying the thing with either the script or the collider
he just copy/pasted the code I gave him without thinking about it
Oh man am sorry for annoying, it was just that i have like a circle but there's 2 cubes instead of 1, then i was triggering one cube that dint do anything
then reference that vine and destroy it
on swing
Then you should call destroy o. The parent of that instead of the parent of the object this script is on
I tried doing it with 'other.', which has the tag I applied to the vine section, but it didn't work earlier
Show the inspectors of both objects involved in the collision
because other is a collider not a transform
The other cube was just another type of script that wasnt on place, am sorry for annoying
Definitely premature. One extra object is not going to cause a noticable performance difference. Later on it can be fixed easily if it does, but you might save a lot of development time being able to visually position the object in the editor
It would not take a long time to fix later either
But it's so exceedingly unlikely to be a performance problem unless there's thousands of these things in the scene
what exactly doesn't work ?
other would give you info of the collision between the two
does someone know how I change the width of a orthographic camera. I can change the size but I need the camera to be long and changing the size only leads to a bigger cube.
afaik that depends on the aspect ratio
also not code question
oh sorry
Hey guys, i want to implement this function for humanoid characters, that when called will disable the animator, and then it will enable the rigidbodies on every limb that has one. I have that part done but its the next part that i dont know how to do.
I want to add a force to each limb, so that they would continue moving in whichever direction with the same speed they were already moving in, when the animator was active.
How do i achieve this?
so a ragdoll
Yes, i want to have death animations that will turn my rig into a ragdoll at some point
I will call the function uaing animation events in the death animation
yeah so whats the problem rn?
If i only used a death animation the character wouldn't interact with the world, and if i only use ragdolls the rig will just drop to the floor. I want to have a death animation, that mid way through the animation turns the character into a ragdoll, and have evrey limb thrown in the same direction they were moving in before the character turned into a ragdoll
Read the original message in its entirety please
eh..I know what you're trying to do
Im asking which part you cannot figure out since you seem to have the process already in mind
How do i know how fast a evrey limb was moving so i can calculate the force required for each limb when the ragdolling function is called
normally animator already moves the limbs so it can just continue from there, you can also keep track the velocity
another way to track is checking where the limb was last frame compared to current frame and that gives you move direction
So a coroutine that saves the location of each limb, waits for end of frame, gets the location for each limb again and subtracts it from the previous frame and then does the ragdolling?
I dont think i would want normalized since i need the limbs to move at the same speed as when the animator was active
Dosnt this have problems with different framerates?
why would it be problem
How to fix this acceleration of vehicle?
Maybe you get a random lag spike causing incosistant frame rate, making it so the prevpos-newpos is higher then it should be.
Some calcultions with time.deltatime should be able to fix it ig
Hello everyone. I'm just digging into Unity and coding and I've gotten stuck. I'm following a tutorial, copying the code written, yet I'm getting the error "The associated script can not be loaded. Please fix any compile errors." The only thing I see different is that my script is colored differently, I thought maybe there was a simple fix somewhere. Any help is appreciated.
dont multiply mous input with time.deltatTime btw
Check the compile issues in the console
You must have anywhere red underline
!ide
π‘ IDE Configuration
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
Mouse input is already a delta why do tutorial youtubers do this anyways lol
Because one guy did it, and they all copy from each other. Most youtube tutorials are shit, especially when it's for beginner concepts
generally copying off each other
it's also a natural mistake if you don't understand why you use deltaTime
if your understanding is "I use deltaTime so that things are framerate-independent", then of course you're going to use it there
I don't think the console helps with this?
please configure your vscode first then it will underline the lines with errors
I thought I did that, but things kinda got messy
Any way to sample a frame of an animation in code? Like for getting the position of a transform, on a specific animation, on a specific feame?
Oh shoot! things are happening, the unity extension wasn't fully installed yet
why does addforce induce a bit of rotation even if applied perfecly through the center of mass, while addforceatposition keeps my rocket flying straight?
you can get an array of keyframes and compare against current time
one or another
i dont know what changed but now they are both working???
i changed a different unrelated part of the code and somehow it got fixed??
they're like the easiest thing to learn lol
I have a tiny brain
you make a Ray and get some data from it
It's easy to understand but hard to grasp fully
pick point, give direction and distance
learn to make the visual debugs for it for easier understnding
the harder concept is the bitwise layer mask
Docs are not making it clear for me
yes their example is stupid
"Optionally provide layermask"
why not just show the layermask type instead of bitshifting
also TransformDirection method randomly put in there lol savage
in edit mode, can I apply the same effects that this eye icon from code ?
i suppose this get the GO and all childs, and disable the renderer ?
most likely yes.
everything in unity editor is done via code anyway
I will understand in time
which part are you confused on exactly ?
okay ty, now i have to find it xD
look into this class
there might be another, gotta look better
https://docs.unity3d.com/ScriptReference/SceneVisibilityManager.html
there is also . nvm
~~https://docs.unity3d.com/ScriptReference/Object-hideFlags.html~~
What does what
like what?
just watch tutorials and youll get it eventually
**keep doing it
watching will not engrain knowledge, repetition does
I used to keep the whole raycast line inside a copy & paste clipboard because i never knew how to make one. the more I used it, the more it made sense and became muscle memory
public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layerMask)
Vector3 origin : starting point in space represented by a Vector3
Vector3 direction : direction vector from the starting point represented by a Vector3
out RaycastHit hitInfo : struct of information from which object that was hit by the raycast (you declare the variable inline using the out ketword)
float maxDistance : distance value represented by a float
int layerMask : bitwise component to filter out layers which you want to ignore or hit
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
https://docs.unity3d.com/ScriptReference/RaycastHit.html
https://docs.unity3d.com/ScriptReference/LayerMask.html
Ill just take from an example and play around with that
Tysm
What I am searching for, if I want to collect items by pointing the middle of my screen to an objects while pressing [E] to collect the item?
I jsut find some cheap guides that only use colliders where it doesent matter in what direction the player is looking but This is not enough!
The player needs to look at the items + beaing inside of a collider, to make sure the player is in range to collect it and to make sure the playing is pointing with the middle of his screen to this item.
is it a first person game? u dont need the collider in that case
Trigger + raycast should do
if (Input.GetKey(KeyCode.LeftShift))
throttle += Time.fixedDeltaTime;
if (Input.GetKey(KeyCode.LeftControl))
throttle -= Time.fixedDeltaTime;
if (Input.GetKey("z"))
throttle = 1f;
if (Input.GetKey("x"))
throttle = 0f;
Mathf.Clamp(throttle, 0f, 1f);
why does throttle go outside the limit? i can just keep holding shift and it goes beyond 1
a raycast should be enough, cause you can give it a range. no need for a trigger
and u wanna have an interface on your collectible items
which limit ?
thats not how Clamp works..
wdym
you never assign the clamp
d = clamp (a, b, c)
why does this matter and why do I not need the collider?
If you want to collect a flashlight, you need to be in range because you dont have 20 meter long arms to collect this item if its to far away.
Plus you need to look at the item.
raycasts can have a range.
can anyone help how do i fix this idk what it is?
show the full stack
like this?
Seems like an Editor error
just make a map idrek tbh
could be Probuilder bug
Did you delete the map
no
basically, when you press E, you shoot out a raycast from your face with a length of 1 meter or whatever, you can decide how long it is. and if it hits something with your collectible interface then you pick it up. look up raycasts and interfaces
Do this then
okay, thx.
do note , the receiving objects do need colliders for raycasts to work
Hello I'm new to Unity and coding and starting my first project, I have a ball im controlling and trying to increase the movement speed when holding down shift, but I don't know how to write the code for that. This is what I thought it would be but clearly it's wrong lol
this is presssed not holding, also read the error it tells you whats wrong
Show the errors I wanna see
more likely you're trying to pass ShiftKey as a keycode in a button(string) function
addorce Im gonna guess youre multiplying two vector3s
should I change addForce?
wwhat?
no you need a direction
oh
Vector3 would be that, find out which direction you want
Ohhh ok I changed m_MovePower to moveDirection
I was wondering if I could get help with an error but I dont want there to be two converations at once should I make a thread?
yes a thread is a good idea
no need just post the question
or yeah make thread
dont listen to me I just didnt have my coffee today
but my ShiftKey is unrecognizable, whats the Shift key name in Unity or do I need to add it somewhow?
Do you mean this? https://docs.unity3d.com/ScriptReference/KeyCode.LeftShift.html
but you cannot use Button for that btw
Unexpected preprocessor directive
change it to GetKey instead of GetButton
ahh okay thank you
GetKey is held and GetKeyDown is pressed once
so im trying to mod a game and need to make an inputfield but its not working, do yall know how to fix this
awesome thank you I didnt know
we don't really offer support for modding sorry
more likely you're missing namespace though
if you mouse over that, your IDE will give you the suggestion to fix it by adding a using directive
the code works thank you guys so much for the help!

it does not unfortunately
I want my raycast to activate a button if it hits it, how should I go about doing this
I have one little question related to boxhelps... and if someone could help me i'll really appreciate it: How do I make Right BoxHelp automatically adjust vertically to the size of Left BoxHelp in real time in this case? so that in height the right always measures the same as the left. This is the both boxhelps code https://paste.ofcode.org/rHEZVn9pNbh8KGBgFxnKjB
depends..what is a Button
a physical object in the world space ?
make script that does what you want when hit, make the method public
you dont , just call it from the script you find on raycast hit
rb.AddForce(transform.forward * reverse * Input.GetAxis("Vertical")); how to do it reverse?
wdyb by "reverse? just a force in the opposite direction?
transform.back doesn't work
-transform.forward
Ok so even if its in another script I can just call the method because it's public?
I did it but still same
it will be opposite
@mellow elbow am i correct saying that an interface is the best option for this
yes if you find the script through hit ray, and method is public yes
What is your reverse variable doing?
Shouldn't that be -1 if you want to reverse it?
yes but it might be a little too advanced for #π»βcode-beginner
its good practice to use Interfaces absolutely
same as speed
What is an interface
Just it have to be different number
same as speed? Why? that's weird. Show more of your code
its a very special type
under what circumstances do you want to reverse
if you want the best option use an interface, if its just some beginner project where u dont really care about the best option just do something like hit.gameObject.GetComponent<Button>().PressButton();
ah
always use TryGetComponent imo
It works but not. It goes reverse about 0.05 and forward goes nice
Difference being?
in case Button isnt found you don't null ref (trying to run a method on something that wasn't found potentially)
yea cuz what if you interact with something that doesnt have a Button component
Anyway thanks it work
just dont name your component Button lol
cause there already is a class like that UnityEngine.UI.Button
and thus begins the hardest decision of all... what to name it instead π
It doesnt have a button component
whatever the name of your component is
its just an example of a class you can make
ah okay
The component is the name of my script right?
naming is probably one of the hardest things in coding
xD
you want the collider first
hit.collider.gameObject
I see
btw gameObject is redudant
if(hit.collider.TryGetComponent(out ButtonScript btn))
btn.Press() //some public method on the button```
i am a moron i somehow forgot to add unity.ui to my references
Like this?? cause it says it doesnt exist in the current context
no
not at all
you need a reference to ButtonScript
stored in a var
OK so I store it first
yes
@mellow elbow like this
as what type of variable
ButtonScript
but yes what I wrote is a shortcut
ah
its the same as this
ButtonScript button = hit.collider.GetComponent<ButtonScript>();
if(button != null)
{
button.Pressed();
}```
how do you do this btw
with the box
that the code is inside of
Three `
you got it working ?
nice!
Is there a way to make the character movement less jittery when in the air? Or is it just my laptop?
well for one you should enable interpolation on your Rigidbody
That didnβt really do much
it should, also how are you moving character (code wise)
Iβm using the Third Person Controller
With some extra bits of code added in where the character is βgroundedβ when on the bottom of the vine, so it can jump off
are you talking about the CharacterController one?
yes that would be character controller, mixing that with Rigidbody collisions is tricky
something you did to controller though is making that weird glitch, you have to show hat you did
the TPC controller script alone doesn't do that afaik
I think it's coming from me disabling and re-enabling the TPC whenever I was in the vine's hitbox
how are you moving it on the vine box then ?
also CC prefers to be moved on the Physics update with Move
It's attached to the collider's position as it swings
Before you ask, I followed a video tutorial on getting swinging to work
It demonstrated the code working with a cube and I was trying to replicate the effect with a proper character controller
was the cube just a rigidbody or what
CC is just tricky to sync with rigidbodies properly
maybe convert to a rigidbody only whilst swinging
This conversation already happened yesterday π€
I have it so that the rigidbody is kinematic whenever I'm not on the vines
Completely disabling it outside the vines makes my character plummet to the ground
anyone know any resources or some tips that might help me make a click -> move top down style selection system.. does the clicker mechanic need its own state machine? you reckno?
is there a way to combine multiple gameobjects into one?
In what sense?
what are you trying to accomplish?
In the scene window. I just spammed a gameobject with a sprite render to create a placeholder level layout, but I want to turn all of these gameobjects into one- is that possible?
You want to create a single sprite out of all of them?
Or you just want to be able to move them all at once?
What are you hoping to accomplish ultimately
to not have the hierachy full of "Forest(xx)"
yeah, that
Put them all under an empty parent object and collapse it
oh that works thanks
You can select a bunch of objects, then right-click and click "Create Empty Parent", btw
My player will not move https://gdl.space/izapivuneq.cs just animating in spot
Hi Can i ask a few question
I dont whats the problem .. im using player prefs to save the data .. and debug say its display but in my screen the stone dont appear
you'll have to show us the code you're using
!code use a paste-bin website.. the compression on thats awful.. i can barely read it on a PC, mobile has no chance
Posting 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.
using UnityEngine;using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PyramidStoneSceneController : MonoBehaviour{
public Image stoneImage; // Reference to the Image component in the UI public Sprite spriteForOneStone;
// Set these values according to your desired position
public float newX = 0f; public float newY = 0f;
public float newZ = 0f;
void Start() {
// Log the initial local position Debug.Log("Initial RectTransform position: " + stoneImage.rectTransform.localPosition);
// Retrieve the collected stones for the previous level
int collectedStones = PlayerPrefs.GetInt("StonesCollected_Level" + (SceneManager.GetActiveScene().buildIndex - 1), 0);
// Debug log to show the retrieved stone count Debug.Log("Stones retrieved: " + collectedStones);
// Display the image based on the number of stones collected
DisplayStoneImage(collectedStones);
// Set the local position of stoneImage stoneImage.rectTransform.localPosition = new Vector3(newX, newY, newZ);
// Log the final local position
Debug.Log("Final RectTransform position: " + stoneImage.rectTransform.localPosition); }
void DisplayStoneImage(int stoneCount)
{ // Debug log to show the stone count
Debug.Log("Stone count: " + stoneCount);
// Display the image only if there is one stone if (stoneCount == 1)
{ // Set the sprite for the Image component
stoneImage.sprite = spriteForOneStone;
// Debug log to show when the stone is being displayed Debug.Log("Stone displayed!");
} else
{ // Set the sprite to null or an empty sprite if you don't want to display anything for other cases
stoneImage.sprite = null;
// Debug log to show when no stone is displayed Debug.Log("No stone to display!");
Debug.Log("Assigning sprite: " + spriteForOneStone);
stoneImage.sprite = spriteForOneStone;
Debug.Log("RectTransform position: " + stoneImage.rectTransform.position); }
}}
Sorry for that
use a paste bin website..
click one of those links in the embed i sent.. and copy and paste it.. it'll give u a link
Orite sure