#💻┃code-beginner
1 messages · Page 368 of 1
The good new is it's not burning fuel like hell anymore,Coroutine runs only once. But it's still burns fuel even the engine is not on/ not clicking
Perhaps there is another problem with Input.GetMouseButtonDown(0)
GetMouseButtonUp is true for one frame
You're probably missing it due to that WaitForSeconds.
yeah the timing would have to be insane
If you just want to know if the mouse button is now up, use GetMouseButton
if it's false, the mouse is not being pressed
right to the millisecond 
Capcom games 
the guys that made resident evil?
only resident evil ?
- many others

we have to include resident evil 2, 3 and 4
where is 1 ?
its behind EA, but EA slowly turned into a cashgrab
wat?
ah sorry but can you tell me where to put it? TwT
EA never touched resident evil lol
I mean in success
not even close
EA got big because of Sport games, mainly publishing*
they had good games they Published but not made.
Notably Freedom Fighters and alike
dead space was good too
well, they have their own game engine at least
I miss dead space
DICE made frostbite yeah. It was good
I need mouse button to hold : (
So what? You can check if it’s currently pressed
You don’t need to know if it was released this frame
It's working for "flame", which appears on hold
If GetMouseButton returns false, you aren’t holding the button
lemme try
for (int i = fuelAmount; i >= 1; i--, fuelAmount--)
while (fuelAmount > 0)
{
fuelAmount--;
}
This runs until you’re out of fuel
ahh yeah you're right
What exactly doesn't work?
Are you talking about my variant? They're the same.
Both won't work in your case
It doesn't stop burning fuel
nah original question is they want to stop burning when they release
if you want to burn fuel until you let go of the mouse, all you need to do is use GetMouseButton, not GetMouseButtonUp
that's it
T_T
you will need to invert the condition, of course
if (!Input.GetMouseButton(0))
this will succeed when the left mouse button is not being pressed
wait
You can say
if the mouse is being held
burn the fuel
and yes, you should really just do this
When I try it, this time I can only click once
also, the for loop is really weird
just do
while (fuelAmount > 0 && Input.GetMouseButton(0)) {
...
}
It's not my code, got it from youtube
yea this can probably be easily just in Update
Why not in Update?
using a coroutine makes it easier to do the 0.2 second interval, I guess
but it'll also be inaccurate, since you'll get more than 0.2 second delays (because the coroutine actually resumes on the next frame after 0.2 seconds pass)
so yes, this really belongs in Update
You can use a float field to store how long until the next unit of fuel is burned
time.time also can help do the intervals
void Update() {
bool burningFuel = Input.GetMouseButton(0) && fuelAmount > 0;
if (burningFuel) {
burnTimer -= Time.deltaTime;
while (burnTimer <= 0) {
fuelAmount -= 1;
burnTimer += 0.2f;
}
}
}
This won't be too different from Update, since both are called there
something like this
This would correctly let you do super-short burns without losing a unit of fuel each time
Although, if you do want that, you'd need to rewrite it a bit
Coroutines are useful for when you might be doing the same thing many times
where it'd be annoying to keep track of everything in fields and handle them all in Update
e.g. spawning a particle system and then destroying it after 3 seconds
(although, in that case, you can just pass a second argument to Destroy to tell Unity how long it should wait)

oh? I thought some software developers at EA worked on it
no it was DICE who was acquired by EA. They got the cash to buy studios out
not sure what you mean by that
But... valve actually made source.
Hello! I am a beginner with unity and I am running in a bit of an issue.
I called a variable "public int points;" and then tried to increment this variable by 10 every time I called the function pointUp but it keeps resetting my point variable to 0 and I always end up having 10 points no matter what I do. Can someone help me?
(I am not in void Update here btw)
You don't seem to be calling pointUp() anywhere in this screenshot
also - why does the function return an int, if it's also modifying a member variable?
It should probably only do one or the other
Add Debug.Log to your code to check when it's running and what it's doing
just modifying point wasn't working so i tried different things
Debug.Log($"Before adding points: {points}");
points = points + 10;
Debug.Log($"After adding points: {points}");```
My guess then is you are almost definitely looking at the wrong copy of this variable
which class is this on?
Is that script on an object that gets destroyed at some point?
Share all the relevant code in paste sites !code
And explain which components are on which objects.
📃 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.
Why is this on TetrisBlock?
You want each block in the game to track its own number of points?
Because that's what you're doing
Called it - destroy a block and its own number of points is lost
Yes we have identified the issue here #💻┃code-beginner message
You should keep the point count in an object that does not get destroyed, maybe that's the original point of using return in the method? So you can get the number of points this block gives, and store it in another variable?
You would need a centralized manager that keeps track of score, yes
because when the block is destroyed it destroys my points
Just think about it. Should each tetris block have its own "score" variable? That doesn't make much sense.
Same thing with the grid etc
these should be part of some central game manager type thing
haa okok
honestly for everything except the points I followed a tutorial
but yeah I get it
thx! I'm gonna try that
when designing your game, it's important to think about who "owns" a concept, as well as how many "owners" you'll have
A block might own its own score (maybe you have special golden blocks that give more points)
but it should not own the total score
why Cant I drag my GameObject parent into the editors GameObject section?
You're looking at the Script Defaults for the INventory Manager script
do I have to apply the script to something before I can link them?
You would need to look at the inspector for a GameObject in the scene that you attached the script to
ah ok
yes... If you haven't dont that, you aren't using your script at all
yea I thought I could just link it before I used it somewhere
When you click on a script asset, you're inspecting the script itself
you can set defaults for when you add new instances of the component
i've never really used that
Reallyyy!?? it is helpful for Editor classes
Yo a while ago someone gave me a website to help me with c# can someone help me remember i know nothing
check the pins
Yo its telling me that i should download an LTS version of unity but i already have normal unity what should i do
the LTS version is about as close to "normal unity" as it gets
Hello, is there someone experienced who could help me make a system like this: https://www.youtube.com/watch?v=UWFuPmEj6xc except in 3D? I think it may be highly advanced and I dont have much time, so I would be really happy if someone could enlighten me on how to do this
#gamedev #unity #unity3d
Wait so do i get LTS or no because cant my game files stop working if there is no support or somthing
no, they won't "stop working"
the long term support version is just a major release of Unity that gets patches for a long time
Interesting. In 2D would be a little headache
If you have an existing project, use whatever version it uses.
If you don't, install the 2022 LTS.
Im on the first steps of unity learn doing a microgame so idk
Yeah... I need it in 3D though, so even harder probably
If you want to use the microgame templates, then you need the 2021 LTS.
The tutorial should tell you this
make sure to read it (:
It does but why cant i do it in normal unity
because the templates were only made for the 2021 LTS
this is also "normal unity"
it's just an older version
And there is 2d platformer microgame on the one i have
Does text have a method similar to button's onClick or should I just use a button and the methods from that for simplicity?
public class ClickExample : MonoBehaviour {
public Button yourButton;
void Start () {
Button btn = yourButton.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick(){
Debug.Log ("You have clicked the button!");
}
}
is this on UI text?
So do i get rid of the one i have and get LTS
I believe so, yes
Wont it get confusing?
Add an Event Trigger component to your Text
if so, you can either:
- implement
IPointerClickHandlerhandler in your component - add an Event Trigger component and set it up
not really.. the hub does a good job of showing u what version what project is using
Yeah I saw that IPointerClickHandler but it seemed a bit excessive when I could just use a button
well a Button is really just a Selectable with IPointerClickHandler on it tbh
Wheres that
when u make a new project u can choose the version to use it
Ohh
just follow the instructions in the tutorial
I am but there confusing
they were written to be followed, not to be completely skipped over
Is there a way to make my button background transparent? Other than setting the color to the background, which I want to avoid in case I change things around
u change the Alpha/Opacity to 0
Oh awesome, I forgot about that. Thakn you
the last number/ lower number in the color picker
Found it, thank you so much
hello it's me again, I made another script to change the number of points but I wanna call it when a block or when a line is detroyed. I tried using "FindObjectOfType<pointManagement>().pointUp(); " in my script that deletes lines but it tells me
"NullReferenceException: Object reference not set to an instance of an object
TetrisBlock.DeleteLine (System.Int32 i) (at Assets/TetrisBlock.cs:83)
TetrisBlock.CheckForLines () (at Assets/TetrisBlock.cs:60)
TetrisBlock.Update () (at Assets/TetrisBlock.cs:45)"
and I have no idea of what it means
You can have multiple editor versions installed at the same time. No need to get rid of any unless you don't plan on ever using that version again.
And you should almost always be using one of the LTS versions unless forced to use an old one by something you need or want to check out the cutting edge changes is brand new versions.
That's a NullReferenceException - the most common error that beginners will encounter
It means you tried to use a reference that wasn't actually pointing at an object
Idk what im doing im just gunna try random stuff till it works
Can you show a bit of the script at the offending lines?
Bad idea
Why
If this was the line that caused it:
FindObjectOfType<pointManagement>().pointUp();
It means you didn't have an instance of pointManagement in your scene.
To just try random stuff until it works? Kinda self-explanatory
good way to break it more and more until its unsalvageable lmao
Just follow learn until you have the foundation to know a little what you are doing
Its fine
I don't get it :/
errors meant to point u directly at the error.. to save time/ trouble/ headaches
What part don't you get? I explained it pretty clearly I think.
point management is a script what do you mean I don't have a instance
like it's not connected to anything?
It is not attached to a gameobject as a component inside the active scene
yeah sorry I'm a beginner beginner
you're saying BlueScript.DoSomething();
and the editor is like yo, guy.. I don't know what BlueScript you're talking about.. its either missing or you didn't tell me which one to use
Show your inspector where you are trying to get the pointManagement object
this?
so I have to create and object and connect my pointManagement to it?
You have to attach your scripts to objects in the scene for them to do anything
if pointManagement isn't on a gameobject in the scene it wont find it..
Well yeah because you're telling the code to find the pointManagment object in the scene
if its a Manager type script or something you can jsut attach it to an Empty GameObject and give it a good name
okok I think I understand thx! I thought that it could work if I just used debug
regular monobehaviour scripts that aren't attached to anything in the scene will get completely ignored when u build.
god it workkkksss thxxx
Celebrate good times
if u can.. you might want to cache the reference in a variable in Start() or Awake()
that way ur not using FindObject every time u run that loop
bad for performance
private pointManagement myPointManagementScript;
void Awake(){
myPointManagementScript = FIndObjectOfType...```
then u can just call myPointManagementScript.pointUp();
you'd already have that reference stored
just a good tip for later.. might be fine for a tetris game.. but depending on how many times that looop runs. and especially if its in an update or something
yeah I understand
why do you use private here?
b/c unless its accessed elsewhere theres no need to make it public
keep things private unless they have to be made public (like in order to access them from an external script)
it's accessed when I update my point no?
yeah or it use more data for nothing right?
well its more like exposure..
if other scripts can access it.. (like when they don't need to)
it could be easy to accidently call a function or rewrite a value u dont mean to..
ha okkk
or if its public in the inspector u could risk forgetting to assign it or something
okok
one last thing, find objectoftype what?
like pointUp()?
and u can still assign it in the inspector if u'd like
you can make a private variable visible in the script's inspector
by adding [SerializedField] in front of it..
like
[SerializedField] private CharacterController myCC;
u could drag it in and assign it in the inspector.. but it wouldn't be able to be accessed outside that class still
the type it is..
just this part
;
and then when u say myPointManagementVariable.pointUp();
its the same as
FindObjectOfType<pointManagement>().pointUp(); (but not really, b/c its already been assigned, ur just accessing that instance of the pointManagement script)
you need to get your !IDE configured
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
after that you should declare the variable in the class
what is that
ur code editor
What is myPointManagementScript?
Ah, yeah after fixing your ide
this
No. What is it in the pointManagement class?
#💻┃code-beginner message
actually this
Hint, it is nothing
lol..
Hmm so the way I'm doing this seems bad in the long run but I have two separate scripts, one attached to my enemy and another attached to my button. Both call the camera to switch. How would you handle this?
Only one should do it
or rather
Would you attach it to the enemy or the UI? Probably the UI, right?
you should make a function that switches to the battle state
in a singleton probably somewhere
and both of these pieces of code should call that function
Interesting, I've never used a singleton I'll look into that
FindObjectOfType() is ❌ deprecated in Unity6 anyway 😈
only because it's been replaced by a version that lets you specify if you care about it being the first object or not
well, by two functions
https://gamedevbeginner.com/singletons-in-unity-the-right-way/ good source imo
Discussion goes a bit over my head, but thank you for that
Any clue why Im getting a null reference when I interact with this object with the Item class on it? The interactions are working correctly, it just stopped working when I tried to get the itemName from class Item
item.cs:
using UnityEngine;
public class Item : MonoBehaviour
{
public string itemName;
public Sprite icon;
public int maxStack;
}
Interact function:
private void Interact()
{
Ray ray = playerCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (canInteract)
{
if (Physics.Raycast(ray, out hit, interactRange, interactableLayer | collectableLayer))
{
GameObject interactedObject = hit.collider.gameObject;
string objectName = interactedObject.name;
if (objectName == "Charging Station")
{
playerStats.ToggleCharging();
}
else if (objectName == "Chip Terminal")
{
ToggleChipTerminal();
}
else
{
Debug.Log("Interacted with: " + item.itemName);
}
}
else
{
Debug.Log("Nothing interactable in range");
}
}
}
well, what is the actual error?
there are plenty of places here that could cause an exception
The item variable did not have a value. Make sure you assigned a value into it before accessing things on it
look at the line number, then verify that everything used on that line isn't null
Yea I assigned 2 different objects with this class attached to them, heres one of them
heres the full error message fen: NullReferenceException: Object reference not set to an instance of an object
okay, and what line is it coming from
You might want to actually get that script on the object you just hit with the raycast, right? Because you're not doing that right now
yeahs, nothing here actually assigns item
yes, that declares a field that holds an item
That targets one specific item. Your raycast might be hitting something else entirely
it doesn't do anything to assign a value to that field!
so I need to get the object im hitting, get the item component from it, then I can get the info from it
Correct.
TryGetComponent is useful here.
if (!hit.collider.TryGetComponent(out Item item))
return; // give up and quit early
item.foo = 123;
or, in your case
if (!hit.collider.TryGetComponent(out item))
return; // give up and quit early
item.foo = 123;
since item already exists
The first one declares a new variable.
That variable should probably be kept local if you're not using it elsewhere
yes -- that simplifies your class
you don't want random cruft floating around
(my cat is sitting on me. help)
it's basically a static instance of a class that you can access from anywhere within the scene b/c there's only (1) version of it.. that way there are no conflicts finding the right instance of it.
https://hastebin.com/share/apewuvelot.csharp <-- basic singleton setup
like here in this TestScript.. you can attach this component/script to a gameobject in teh scene and w/o having to assign any more references you can access it from any other script.. like:
TestScript.Instance.MethodYouCanCallFromAnywhere();
A singleton is anything that should only ever exist once -- not zero times, not two times
great for things like Score Counters, AudioManagers, GameManagers, etc
"game controllers" are often singletons
I have a set of singletons that only exist in individual levels, and then a set of singletons that exist for the entire life of the game
only way i like em! 😈
de nada.. i was just pasting the relevant snippet of code from that source i linked.. as u mentioned it was a bit over ur head..
that way u can kinda focus on the important part of it.. and work it out
public class Widget : Singleton<Widget>
{
}``` my singletons are *tiny* now, I love it ❤️
OnApplicationQuit() is called before OnDisable() :(
Is there a way to make sure it does OnDisable first
Well, you could finagle something with Application.wantsToQuit:
https://docs.unity3d.com/ScriptReference/Application-wantsToQuit.html
like disabling the object you want OnDisable called on, or just doing the behaviour manually
I see, I think i will use OnDisable instead of OnApplicationQuit and change the execution order
Why would you need to do this? What's specifically the issue you're having?
There are definitely better alternatives
Backend API subscriptions. Basically I just want to unsubscribe to everything when the app closes, just to have a clean exit
this only really matters if you have Domain Reload disabled
which only matters in the editor
Still, it feels more clean to actually do the unsubscriptions.
Btw I solved this using OnDestroy
one thing I've noticed is that, when the scene is being torn down as the game quits, objects can start comparing equal to null immediately after they get destroyed
(rather than this waiting to happen at the end of the frame)
I have a singleton class that instantiates a prefab if an instance isn't available
it wound up spamming lots and lots of copies of the prefab
the new update makes inline code look soo much more presentable 🙂
Exactly that is the issue I was having
I need to go look at that again
maybe make a small test project to really figure out what order stuff is happening in
OnDisable gets called on everyone before OnDestroy does, iirc, so you can subscribe and unsubscribe in OnEnable and OnDisable instead
...but sometimes I really need to stay subscribed at all times, even when the component is disabled
Oh no, I've solved it now :)
(e.g. I want to be able to enable the component in response to an event)
using main.model;
using main.service;
using UnityEngine;
namespace main.mono
{
public class GameCloser : MonoBehaviour
{
private void OnDestroy()
{
ServiceManager.Instance?.CloseAll();
GameSaveManager.Instance?.Close();
}
}
}
That was all I needed in my case
They aren't mono behaviours
Ah
Make them implement IDisposable 😃
public static bool Safe => _instance != null;
this tells me if the instance either doesn't exist at all or got destroyed by unity
I have Domain Reload off, so I have to make sure everything unsubscribes from static methods properly. I also try to unsubscribe from everything else so that I'm certain the game will behave properly as I go back and forth between scenes
(even outside of the editor, forgetting to unsubscribe from something that lives longer than you is a problem!)
Sorry to bother anyone, but I am struggling trying to figure this out. When I start the game, my player movement doesn't want to function.
moveDirection = cameraObject.forward * inputManager.verticalInput;
this is the line that the error is finding, and im not really understanding why.
Start from sharing the error
what error?
The null reference is going to be cameraObject or inputManager (or potentially verticalInput, but that is likely a value type, so cannot be null).
Assuming that code is PlayerLocomotion line 31
Very very stupid question (probably not coded related), but does someone know why I cant click on the elements of my canvas?
I can move the elements changing the transform values, but I dont know what option I touched that I cant move them using the mouse in the editor
oh thanks man
Getting hit with the classic noob dilemma of not being to use the + operand for type Vector3 and float. What I'm trying to do is add a positive-y offset to my camera which is hard coded to follow the player. The focus.position being that it's centered on the player. I can give more info as needed. Hope this question was clear!
sorry again for posting here, didnt found the UX place
Full function if it helps at all. And to be more specific by default the focusPoint is the centered of the player model.
You can't add a float to a vector, but you can add a float to the vector's y component
using UnityEngine;
public class FollowSquirrel : MonoBehaviour
{
private SquirrelMovement squirrel;
private RectTransform rectTransform;
private void Start()
{
squirrel = FindObjectOfType<SquirrelMovement>();
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
Vector2 screenPos = Camera.main.WorldToScreenPoint(squirrel.transform.position);
rectTransform.localPosition = screenPos;
}
}
im trying to make a UI object follow the screen position of my gameobject, the movement is right it is just weirdly offset and this offset changes when the screen size changes (i.e if i drag the game window to make it bigger/smaller the offset will shift) anyone know why this is occurring? Seems like it would be an easy fix but google is unhelpful on this
Feel like I'm missing something obvious.
bleh
Its readonly you cant modify it like that
Vector3 myVec = focus.position;
myVec.y += cameraOffset;
Vector3 targetPoint = myVec;
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
Also you should configure your !ide. I dont see error highlighting in the screenshots
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
Ok. Thought I did configure the other day but might have done it wrong.
Sorry and thanks.
So I tried to make a certain custom button change transparency on hover
public class ButtonHighlighter : MonoBehaviour
{
private void OnMouseOver()
{
Debug.Log(gameObject.name + " highlighted");
}
private void OnMouseEnter()
{
Debug.Log(gameObject.name + " highlighted");
}
}
But it won't fire, neither on Canvas elements nor game objects.
I mean it's simple, as shown in the Documentation, but won't do...
What am I doing wrong here? (or is it the facts it's 3am here?)
OnMouseOver etc are not for UI
what?
Use IPointerEnterHandler / IPointerExitHandler
did you read the docs?
Yeah, maybe I overread it
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html
This function is called on Colliders and 2D Colliders marked as trigger when the following properties are set to true:
It's for objects with colliders
Not UI
I really should call it a night XD
Actually first line:
Called every frame while the mouse is over the Collider.
update on this...
i am printing out the screenPos and it prints the correct coordinates, however for some reason, although I am setting the rectTransform's position exactly to that, it is the wrong values. e.g. screenPos prints 888, 417 and the rectTransform gets set to 1765, 958. I am guessing it has something to do with my canvas setup or something but I am using localPosition so I am a little confused, interesting that it is double (roughly) the printed coords
Screen space and canvas space are not the same
can I do a conversion?
Yes but it's complicated
Like you suspected it depends on your canvas settings as well as your canvas scaler
Some of this can help
RectTransformUtility.ScreenPointToLocalPointInRectangle
Something like that but it is not so intuitive
My favorite way is to just use Screen Space - Camera canvas
and then you can basically just put things at world space positions and it works IIRC
i think I do have a camera canvas set up
if you mean like an orthographic camera ontop of the ui
Like literally:
rectTransform.position = squirrel.transform.position;``` when you use screen space - camera
I mean the canvas being set to Screen Space - Camera
given that camera is same camera as world camera, yes
lol i have this as well
just tried it
And?
using UnityEngine;
public class FollowSquirrel : MonoBehaviour
{
private SquirrelMovement squirrel;
private RectTransform rectTransform;
private void Start()
{
squirrel = FindObjectOfType<SquirrelMovement>();
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
Vector2 screenPos = Camera.main.WorldToScreenPoint(squirrel.transform.position);
print(screenPos);
RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPos, Camera.main, out Vector2 newScreenPos);
rectTransform.localPosition = newScreenPos;
}
}
its even further off now
Sometimes it is
render camera?
ui_cam
oh yes
So it is not the same cam
of course it's possible
When I'm lazy I just use world space canvas on the character
last resort maybe
I mean in this case you could do:
Vector3 localPos = gameCamera.transform.InverseTransformPoint(squirrel.transform.position);
Vectot3 worldPos = uiCamera.transform.TransformPoint(localPos);
rectTransform.position = worldPos;```
(I think)
ill try
*given that both camera has same settings
yeah if their projections/fov/orthographic size etc are different that further messes things up lmao
well they are lmao
i shouldve probably been more specific
they r both orthographic just in different spots
RectTransformUtility is "proper" way to do
positions rotations/scales are fine
While verbose
they just need the same orthographic size and projection type
But yeah RTU is the robust way to go
does it matter if one is an overlay?
no
Object reference error here. But in Start() I set it buttonTExt = GetComponentInChildren<TextMeshProUGUI>();
The child of the object with this script on it has a textmeshpro ui component on it?
Either:
- Start hasn't run yet
- You don't have such a component on this object
is the object with the script active?
Its a button with textmeshporugui under it
is it the correct component?
those are the two options
Why would strat not run
When you have eliminated the impossible, whatever remains, however improbable, must be the truth
Sherlock Holmes
If theirs no update does that matter?
- This is running before Start
- Your object isn't active
- The script is disabled
- The object is a prefab
None of those are true though?
completely irrelevant
Prove it
also
show the full stack trace of your error
yeah looks like the wrong line entirely
If this error is happening on line 23
then line 24 won't run at all
can you post the actual error lines from your script?
You need to fix this error first
this will make line 24 not run at all
I am so sorry i did not realize i tried to use the component before i even used GetComponent
It's been a bit
Ive got it now
Vector2 screenPos = Camera.main.WorldToScreenPoint(squirrel.transform.position);
RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPos, uiCam, out Vector2 newScreenPos);
rectTransform.localPosition = newScreenPos;
this is super close, the issue now is that its moving in the correct direction whenever my player is moving, but its just not moving enough? but it starts in the correct position and everything idk whats happening
I do have cinemachine so my thought is that is whats making it mess up?
So RectTransformUtility.ScreenPointToLocalPointInRectangle convert your position into local position of rect transform
Thus you'd want your transform's parent
To go in the first parameter
rectTransform.parent as RectTransform
this works? or no
Well that works, not pretty
And remember that your rect transform's position is based on your pivot
yup that did it
love you @void thicket
that shouldnt have taken that long but i learned something so ill call it a win
With TextMeshProUGUI, I have multiple menu buttons. And when i hover over them i want the buttons outline width to change to 1, WHy does this change very instance of this buttons outline width?
buttonTExt.outlineWidth = 1;
Am i supposed to change something else?
Well - that depends - what does your code look like?
Based on the docs it should create a new material instance so I would expect it to only affect that one button: https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/api/TMPro.TMP_Text.html?q=outlineWidth#TMPro_TMP_Text_outlineWidth
So maybe something else in your code is off
Well even just changing it in the inspectro
changin in the inespector I would expect to affect them all
if i Ctrl D - Duplicate the button, and manually change the width of 1, it does it
because that changes the material
Is their a way to not do that in the inspector?
give them different materials
Hi guys, I have this issue where a boolean value is set to true based on the current input and the previous input. The problem is that that variable will stay true only for a few frames and it will go back to being false. What I want it for that variable to stay true, even if the condition turns out to be false.Is there a way I can program the boolean variable to wait till it becomes true and once it is true, I can manually set it to false when a condition is met?
This is really vague.
Anything is possible with the right code. Maybe show what you have and explain exactly what the behavior should be?
at a simple level though:
myBool = myBool || theCondition;```
or maybe more understandably if you don't know boolean logic well, just:
if (!myBool) {
myBool = theCondition;
}```
Hey guys. I want to snap and object around its local Y axis as shown in the image through code. How would i go about changing the objects forward facing direction while keeping its perspective. (kinda like making it spin on its y axis but without the spinning, i just want to hard set it.)
what do you mean "hard set it"?
if the object was completely vertical, I could do transform.localRotation...and sets its y value
but its not so all 3 values need to be edited.
If you want to rotate the object around its local y axis just do transform.Rotate(0, 90, 0)
that would maintain its perspective?
idk what you mean by "maintain its perspective"
it will rotate the object around its own y axis
perspective means basically how the object looks to the eye
90 degrees clockwise around it, in this case
Any rotation would of course change its perspective
No, the object will have rotated around its y axis
so it won't remain the same way
The fov would not change, but the perspective would, by definition.
Even translating tiny bits side to side would change it
image 1 has a rotation of 90 and image 2 has a rotation of 0 but to my eyes they look the same. I want image 2 through code
Are you asking how to actually change which way is "forward" for the 3D model itself?
To do that you need to edit the mesh in Blender.
The object looks like it has rotated 90 degrees counterclockwise in these two images
no. i just want to change it in game as shown by the images
So what you are saying the object is identical on all sides?
to do that you would do transform.Rotate(0, -90, 0)
Then it will look the same 🤷♂️
Perspective is the wrong word for that imo
yeah IDK why you're using the word persective. You just mean you still want it to be tilted over like that I guess
yes
rotate is an addition. I have the final value i want it to be which will constanly change.
put it under a parent object with the tilt, then set localRotation or localEulerAngles
Or just compose the tilt and the y axis rotation as quaternions, if you're comfortable with them
that wont work as the tilt is done on spawn
i can't change the color of my outline on text but when i change nothing in the code and save it mid play, it somehow changes the outline color
can anyone help with that?
both of those will work, I don't see how "the tilt is done on spawn" matters
the problem will just affect the child object rather than the parent. I have tried this approach before.
It will not, if you do it correctly
nvm, ill figure something out
I mean, I've given you multiple working solutions
You will come around to something similar
The only way that wouldn't have worked is if they did something weird with it.
Showing what they tried would have helped in diagnosing that
what weird stuff we talkin' here? 😉
I dunno, non-uniform scale on the parent was my first guess
But maybe something more.... interesting ? Haha
ohhh, that's the stuff . . .
or they applied rotations to the wrong objects or used the wrong thing between rotation and localRotation
I'm working on a rigidbody player controller, I'm manually setting the velocity of the player through rigidBody.linearVelocity = new Vector3(inputVelocity.x, rigidBody.linearVelocity.y, inputVelocity.z);, and I'm using Debug.Log(new Vector3(rigidBody.linearVelocity.x, 0, rigidBody.linearVelocity.z).magnitude) to read the horizontal velocity of the player. The rigidbody's gravity is enabled and is default (9.81). When the player is on the ground and their movespeed is 10, their horizontal velocity is 9.94114 instead of 10, but when they are in the air, it is 10. I made sure the ground material's dynamic and static friction are 0 as well as it's bounciness and I made sure the rigidbody's drag is 0 but this problem still occurs. Can anyone explain why and how to fix it?
Any clues on why my line is refusing to draw?
show the full code
does anybody know why the sword keeps jittering i cant figure out wy
This is really vague.
because it's a dynamic rigidbody that's colliding with stuff as your script forces it inside other objects
and gaining velocity
thus fighting against your code
oh ok
You can use the layer matrix to disable collisions between the sword and ground (and likely walls), or have your code NOT force it into the ground and walls
Or just call the jittering purposeful and leave it
I don't see any good reason that sword should be dynamic
if it's fully controlled via code
im trying to replicate the deepest sword sword mechanic
Oh yeah. That is a good point (what praetor said)
When using LineRenderer how do I break the line when the mouse is let go?
private void Update()
{
if (Input.GetMouseButton(0))
{
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
currentPosition.z = 0;
Debug.Log("currentPosition " + currentPosition);
Debug.Log("InputMousePosition " + Input.mousePosition);
if (Vector3.Distance(currentPosition, previousPosition) > minDistance)
{
if (previousPosition == transform.position)
{
lineRenderer.SetPosition(0, currentPosition);
}
lineRenderer.positionCount++;
lineRenderer.SetPosition(lineRenderer.positionCount -1, currentPosition);
previousPosition = currentPosition;
}
}
}
what do you mean by "break" the line?
The line is currently being drawn but when I let go of the mouse it continues to draw
1 connects to 2, I know it's hard to see
how would i go about getting the name of an GameObject that just triggered a OnTriggerEnter?
It shoiuldn't since your doing if (GetMouseButton(0))
Or do you mean when you click again it does that
just access the collided GameObject from the collision . . .
.name on the collider
When I click again it does that
yeah makes sens
you would need another line renderer
or you would need to make a section of the line between the clicks have 0 width
The other issue is that my color isnt changing despite being set in the inspector
are you checking gameobjects name comparison 🤨
!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.
found a fix. I just subtract the current y rotation from desired rotation and used the product in transform.rotate
Well, that is certainly one way to approximate just setting it. Glad it works for you!
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
to the three people that responded, imagine im very stupid and dont know how to do them, cause im not sure where to put .name, dont know how to access the GameObject from collision and cannot find how to on the API, and im not sure how to check gameobjects name comparison
perhaps you should start here !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
not a problem. i'd start with some learning courses to understand the basics, but you can actually copy/paste your question in
to find answers. just add "Unity" at the beginning . . .
solved the problem, the capsule collider didn't have a material on it and therefore had friction with the floor
just other.name would be the same
so it would
So with this, hit is the raycast name variable we're checking for? So all raycasts begin with Physics.Raycast? And the out hit specifies the bool we're trying to compare to?
hit is not a bool
it is a RaycastHit
the Raycast function returns a bool
which is why you can put it inside the if
it also populates that RaycastHit variable in addition to returning a bool
it is able to populate it due to the out thing
is the raycast name variable we're checking for
This part of your question doesn't make any sense to me
what is a "raycast name variable" and what would it mean to "check for" it?
Trying to move over to Unity and C# from Godot. So I'm used to just doing if raycast_named_this.
The bool would be in the return and in turn I use that variable.
I don't know how Godot works, and that seems strange to me
Yes unity does the same
Raycast returns a bool
The raycast function fires an imaginary ray into the physics scene according to the parameters you give it. If it hits something, it returns true. If it doesn't hit anything, it returns false
pog
bool hitSomething = Physics.Raycast(...);
if (hitSomething) {
// do stuff
}```
you could write it in this more verbose way if you wish but it's usually more convenient to just do if (Physics.Raycast(...))
Gosh I'm loooking at the Godot docs for raycast and they're not very good
Godot's raycasts are overly complicated
Gotcha. Trying to make a specific variable name to reference for complex bs.
Seems like it returns a map/dictionary and the whole thing is just falsey if it hits nothing?
I do feel spoiled by unity docs pretty often
Especially working with all these pre 1.0 cargos for rust lately, with no description for any api call, just the names
this is what dynamically-typed languages do to a mf
everything's just a goddamn shapeless dictionary blob
And if you don't use the raycast node you gotta set up a raycast query through the world, and it's like man let me just fire a ray 
Apprarently all of the Godot C# docs just use var for all variables making it impossible to tell wtf is going on 😦
In Godot you can also just make a raycast Node, define the direction and length, and can drag and drop it into your code as a bool. It's actually easier for me to comprehend but just less powerful which is why I wanted to learn C#.
a raycast Node, define the direction and length, and can drag and drop it into your code as a bool
wat
I don't really know what nodes are tbh. Is that visual scripting stuff?
And that's fair. Even when I was learning Godot I didn't like the sheer amount of vars I'd see on the top of the script. Plain C# makes more sense than Godot C#.
Nodes are their game objects
Confusing
Well more like if a component became a game object, as each node is a single "type" of a thing. And the inspector shows its inheritence tree.
You need raycast component?
How do I learn how code something without just searching up a tutorial every Time I want something done? Ik it takes experience but is there a way to do that without it or just sitting and writing code?
The advice I was given was to start with projects smaller and simpler than you think you can make and try to rely solely on documentation and/or forums.
IF you're good enouggh you can use chat gpt to generate some ideas. But it is never always correct, and often wrong, but can still be utilized
Learn the fundamentals, instead of trying to make specific things in your game work
Like in Super mario bros, when the player is hit or gets a power up, It hads a nice animation where the players transparency fades off and on rapidly. How can i recreate this affect? I tried accessing the alpha of the material and it does not work, i am in urp.
2D? 3D?
Meshrenderer? SpriteRenderer?
3D, Mesh Renderer
You will need to be using a transparent material for transparency to work
Like the shader?
The material
I can set it to Transparent instead of Opaque, But It does not recieve shadows or cast shadows, even though set to On in mesh renderer
Yeah it looks very weird without shadows?
what can I do about that 😭 ?
Do i just duplicate it without mesh and turn shadows on?>
Probably that. IDK
{
private void Start()
{
startYScale = transform.localScale.y;
}
public CharacterController controller;
private float movementSpeed = 12f;
public float walkSpeed;
public float sprintSpeed;
public float gravity = -9.81f;
public float crouchSpeed;
public float crouchYScale;
private float startYScale;
public KeyCode sprintKey = KeyCode.LeftShift;
public KeyCode crouchKey = KeyCode.LeftControl;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
private void StateHandler()
{
if(isGrounded && Input.GetKey(sprintKey))
{
movementSpeed = sprintSpeed;
}
else if (isGrounded)
{
state = MovementState.walking;
movementSpeed = walkSpeed;
}
else
{
state = MovementState.air;
}
if(Input.GetKey(crouchKey))
{
movementSpeed = crouchSpeed;
}
}
private void Crouch()
{
if(Input.GetKeyDown(crouchKey))
{
transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
}
if(Input.GetKeyUp(crouchKey))
{
transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
}
} ```
public enum MovementState
{
walking,
sprinting,
air
}
// Update is called once per frame
void Update()
{
Crouch();
StateHandler();
= Vector3.ClampMagnitude(, 1);
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * movementSpeed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Hello
@wintry quarry
You should store x and z variables in a vector instead
Then you can clamp it as per my example
Oh wait
You do already
It's called move
ohhh i get it now
it says i cant use it before its declared
move = Vector3.ClampMagnitude(move, 1);
nvm
i just moved it in front
sweeet thanks so much
Pretty sure you asked this before, if not my bad. Dithering is a common technique instead of transparency. Transparent objects will also suck if they have complex geometry and you'll see it render within itself even at 1 alpha
i got a sword and i made it so whatever direction my mouse is facing the tip of the sword faces and its working all good but now idk how to attach my sword ):
Wdym by "attach my sword"?
I know what you're trying to do.
I still don't know what you mean when you say "attach my sword"
well the sword doesnt follow the player it kinda just sits there
Oh this movement stuff is pretty advanced actuallly
You would make it a child of the player at the most basic level
yeah i tried that but then if its a child i cant add the rigidbody and get it to work so the sword can affect the player or am i going about this the wrong way lol
you're going about it the wrong way. If you want that physics movement it's going to be pretty complex. Probably attaching the sword to the player with a physics joint
and applying drive motor force on the joint to rotate it for example
it's not exactly a beginner thing
public float brakePower = 1; // 1 stops at 1 second, 2 stops at 0.5 seconds
public float positiveAcceleration = 1;
void FixedUpdate()
{
Truster.gameObject.SetActive(WillMove);
if(WillMove)
{
speed = Mathf.MoveTowards(speed, maxSpeed, Time.fixedDeltaTime * positiveAcceleration);
rb.velocity = transform.up * speed;
}
else
{
speed = Mathf.MoveTowards(speed, 0, Time.fixedDeltaTime);
rb.velocity = transform.up * speed;
}
}``` can I get some help with `brakePower` logic
what kind of help are you looking for?
What are you trying to accomplish?
basically i want it to slow down as the comments say
But wouldn't the time to slow down depend on the current speed?
move towards not the right thing to use
if current speed is 10, it will currently take 10 seconds to halt
Because slowing down from less than max speed should be faster than from max speed right?
yeah because you're doing 1 per second
10 / 1 is 10
10 seconds
yea so what is supposed to be changed?
You would need to answer my clarifying question first
here^
current speed
that... doesn't make a lot of sense
no matter how fst you are, i want it to stop exactly 1 sec
because current speed changes all the time
when you're halfway through braking, current speed is half of what you started braking at
so you mean.. speed at which you started braking?
you'll need to record whatever speed you were going when you started braking then
yea
then it will be:
speed = Mathf.MoveTowards(speed, 0, Time.fixedDeltaTime * (startedBrakingAtSpeed / brakePower));```
but you need to make sure you set startedBrakingAtSpeed properly elsewhere
then, id have to like edit my willMove
to a prop that catches curent speed when falsed
no you just need to set startedBrakingAtSpeed when you start braking
this is one way, sure
shouldnt lerping be fine there? you'd need to setting the lerp time same way you'd be recording the startedBrakingAtSpeed
sure either way would work
both Lerp and MoveTowards result in linear changes over time when used properly
Lerp is unlikely to be used properly in this server though 😆
go.GetComponent<EventXmlRow>().Init(node, attr);
Regarding this piece of code, is it possible to make the GetComponent type variable ?
wdym by "make the GetComponent type variable"?
can you show an example of what you would like to achieve here?
Because this class is used as a base class with an init function
I'm creating several child classes based on this and I want to init those child classes with their own new init function
wouldn't those child classes just override Init?
They do
the code that actually calls this wouldn't change then
go.GetComponent<EventXmlRow>().Init(node, attr); < this stays the same
I'm not sure I understand this answer
When you override a function, it replaces the behavior of the parent function
Currently, this line will call the Init function of the base class
Not if you overrode it
Yes exactly
``using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using UnityEngine;
using UnityEngine.UI;
public class EventXmlRowTrigger : EventXmlRow
{
public Dropdown dd;
private static string[] labels;
private static string[] codes;
public new void Init(XmlNode node, EventsXmlAttribute xmlAttribute)
{
SetLabel(xmlAttribute);
this.node = node;
attribute = xmlAttribute.code;
if (labels == null)
{
labels = GetLabels();
codes = GetCodes();
}
string value = node.String(attribute);
dd.options = labels.ToDropdownOptions();
dd.SetValueWithoutNotify(GetIndex(value));
}
public void OnValueChanged(int value)
{
node.SetAttribute(attribute, codes[value]);
EventXmlRowEventCode.instance.TriggerMode();
//Debug.Log(EventEditor.doc.OuterXml);
}
public string[] GetLabels()
{
List<EventsXmlEnum.Trigger> list = Enum.GetValues(typeof(EventsXmlEnum.Trigger)).Cast<EventsXmlEnum.Trigger>().ToList();
List<string> values = new();
foreach (EventsXmlEnum.Trigger value in list)
values.Add(EventsXmlEnum.TriggerLabel[value]);
return values.ToArray();
}
public string[] GetCodes()
{
return Enum.GetNames(typeof(EventsXmlEnum.Trigger)).ToLower();
}
public int GetIndex(string value)
{
for (int i = 0; i < codes.Length; i++)
if (codes[i] == value)
return i;
return 0;
}
}
``
If you override it properly, it will call Init of the derived class.
Ups
When you override a method, it's as though that method has been completely substituted.
you did new void Init
that is not how you override things
Oh
override void Init is how you override it
and the base method needs to be virtual or abstract
Ah... What's the difference with new ?
new doesn't override
Oh, got it.
it makes a completely unrelated method
Ok I see. That makes sense. I'll updte my code. Thanks !
And the difference between virtual and abstract ?
abstract doesn't have a base implementation
and forces the child to implement it
virtual has a base implementation and it's optional to override it
the base class will need to also be marked abstract in that case, just FYI
Ok thanks! That's exactly what I need.
Hm, I've marked both the base class as abstract and the init method as abstract and changed new to override like said but the base init has the following error now "Cannot declare a body because it is marked as abstract"
What's a "body" in this case ?
{
Debug.Log("This needs to be overwritten...");
}```
Like I said, abstract cannot have a body
public abstract void Init(XmlNode node, EventsXmlAttribute xmlAttribute);
An abstract function will only have a signature
and leave the implementation to the overriding child class
Ohhh
Ok I understand
I removed the body. I didn't know the stuff in { } was the body. but that makes sense.
Thanks again 😉
Great, it's working as expected now, thanks a lot!
Mornin' all. Really silly/stupid maths question, but multiplying a number by 1.1 is the same as adding 10% right? lol.
Yes
Okay, thanks. No idea why but my brain just wouldn't wrap itself around that. lol.
How do I change the text of my button?
public Button mButton;
void Start()
{
Button button = mButton.GetComponent<Button>();
button.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
mButton.text = ""
}
what? why ?
public Button mButton;
void Start()
{
Button button = mButton.GetComponent<Button>();
Why do I want to change the text of my button via script?
no why the GetComponent
Button doesn't have Text
the text is a separate component on a child object
Oh I see
TMP_Text likely of this type
I'm using legacy
Text then
How do I get the child object from mButton?
but yeah this is a good question
Why not just assign it in the inspector
public Text myText;
public class HintSystem : MonoBehaviour
{
public Button mButton;
public Text mText;
void Start()
{
mButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
mText.text = "a";
}
}
Fixed it up a bit
that's fine
but why add the listener in the code and not in the inspector of the Button?
nothing wrong with it but, when it is done incompletely, as in the code above, it exposes a vulnerability
it doesn't recognize the UI namespace . . .
yea i already know that
but why
it doesn't recognize text mesh pro aswell
and many other things
althought its just IDE, no errors in console and can enter playmode/build
Maybe regenerate project
i tried that already
looks like your configuration broke . . .
Switch to Rider 
it just worked yesterday
item.EndDrag();```
Does this not work? Item does contain a public method EndDrag
IDE says you don't have one
it works in other places:
Maybe it's not same Item they are looking
probaly it's trying to use Item class from another asset
ah forgot to add the namespace 🙂
I think Item is too generic for a class name
Hey. So when i load a new scene, my main camera gets destroyed (as it should) but then i get null errors when the new scene starts for stuff that uses the main camera.
When you say "stuff that uses the main camera" Can you be more specific?
As in - Camera.main?>
If so - you need to make sure the camera in the new scene is properly tagged with the MainCamera tag
yeah sorry, so i use the main camera for input stuff, getting the reference in start - cam = Camera.Main
See here
it is,
private void PlayerInput()
{
if (!IsOwner) return;
mousePosition = Input.mousePosition;
mousePosition = cam.ScreenToWorldPoint(mousePosition);
}
Heres the exact code btw, and remeber im setting the reference in start.
prove it
In Start of what exactly? Show more details
Does the camera exist when Start runs?
What error are you seeing exactly?
show the camera's inspector
You said "null errors" but didn't elaborate
So you are setting camera in start
Then camera got destroyed
yes
It won't pick up new camera automatically
That's a MissingReference exception not a null error
you are caching the camera from the old scene i assume
my apologies
You are still referencing the old one
one fix here is simply not to cache the reference
but start is called when a new scene is laoded no? or am i mistaken
i.e. just use Camera.main every time
you are mistaken
Start is called only once per object
when that object first starts its Updates etc
If the object is DDOL, it won't Start again in a new scene
thanks, does calling Camera.Main every frame have a biger impact than using the cached reference?
slightly
You can subscribe to SceneManager.sceneLoaded if that is what you need
Most likely not a concern
does it? i heard it's cached now
It's still a method invocation (property) and probably an if statement
compared with a field access that is slightly slower
Camera.main is my guilty pleasure.
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
NetworkManager.SceneManager.OnLoadComplete += SceneManager_OnLoadComplete;
}
private void SceneManager_OnLoadComplete(ulong clientId, string sceneName, UnityEngine.SceneManagement.LoadSceneMode loadSceneMode)
{
cam = Camera.main;
}
this works, thanks again!
You'll want to make sure you unsubscribe if/when this thing despawns too
Hello!! Is there a documentation about win32 api (Windows system)?
There absolutely is, and it has absolutely nothing to do with Unity
Ok thanks!! :))
I want to test win32 api and how it works
then you should be making a desktop app, not using Unity
I'm using unity 2021
and?
I saw a game called KinitoPET and it's using win32 (KinitoPET Made with Godot) I want to make it in unity or smth
I saw codemmonkey tutorial about Transparent app in unity
my point was, if you want to learn the win32 api you should be making a desktop app which is specifically designed to give you access to that api rather than Unity which is not
What about PINVoke in C#?
Wait i saw this
you can do all kinds of stuff. The question is how will you know what, where and how you have screwed something up without at least a basic understanding of the underlying code
What do they use WinAPI for?
Unity already wraps most of what you need
Control windows system, window apps and more
Ok
I bet what they did in that game is wrap the game in a C++ windows desktop program. That is ceetainly the way I would approach it
Windows is written by C++ the most
if you want real low level access to the OS, yes
Ok :)
C++ and C
I don't think anybody writes windows desktop programs in C anymore, it's been over 20 years since I last wrote one
It's used a lot for low level stuff. But I was commenting the "windows is written in C++" message
I took that to mean user written programs not windows internals
indeed a lot of windows internals were written in both C and ASM
Hey guys i need help, i want an object to go to a point and slow down exponentially until it reaches it, can anyone help?
Should it ever reach that point?
yes
Move towards the target and have the distance be a factor
ok ill try that but one thing i want it to go towards another object theyre both children objects how can i translate the positions?
Is there an issue with coordinates? If you're using coordinates of the same space, you'll not have to do any converting.
ie world space
they have different relative spaces
theyre both children of different objects
That shouldn't be an issue if you're using their world coordinates (position instead of localPosition)
hey guys
What you'd see in the inspector would be their local position.
so smth like this?
hey guys
Unless you're only needing the x axis
my charactr player in unity is weird
can you help me please my player character is weird
ya only the x
How to properly post code questions #854851968446365696
can you help me , idk why is this happening , with the player
!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.
can you help me with this issue
i want to make an interaction system. Before going to look for tutorials: to show the nearby interactable objects, should i go for an OverlapSphere? or a collider on the player GO? and would it be heavy to call it on fixedupdate?
hello
i was thinking of going with overlapSphereNotAlloc and limit the target pool to the default layer, that should be enough?
that sounds fine
https://hatebin.com/kplbjgrbpy im trying to make a cube go up and down continously between 2 points but all it does is go up to infinity and never come back to its desired spot
because youre never applying a different position other than it going up
i set the if statement to set the endposition to startposition so shouldnt it go back down with the newly applied position
wait ur right
okay nvm im just going to set a box collider with a trigger and use that
the issue is the value will never EXACTLY match the endposition cuz it has like 100 decimal numbers
You could use a lerp
people keep telling me to never use lerp
void Start()
{
startTime = Time.time;
journeyLength = Vector3.Distance(startPoint.position, endPoint.position);
}
void Update()
{
float distanceCovered = (Time.time - startTime) * speed;
float fractionOfJourney = Mathf.PingPong(distanceCovered / journeyLength, 1.0f);
transform.position = Vector3.Lerp(startPoint.position, endPoint.position, fractionOfJourney);
}
basically this acts like a sine wave function
thanks
You can also use an offset on the if statement instead. something like
public float offset = 0.1f;
private void Update()
{
transform.position = Vector2.MoveTowards(transform.position, endPosition.position, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, endPosition.position) < offset)
{
endPosition.position = startingPosition.position;
}
}
the lerp isnt working btw```
private void Update()
{
Vector2.Lerp(startingPosition.position, endingPosition.position, Mathf.PingPong(Time.time, 1));
}
i see..
thanks
I got these errors the moment i saved my player map asset. They don't go away and don't let me start playmode. Anyone knows how to fix the bug?
Or you can use LeanTween with the the pingpong loop if you want the animation with a specific ease (https://easings.net/) instead of lineal movement
have u also changed it to vector2.distance in ur start?
Looks like you have a duplicate file
whats leantween?
wdym?
why is if(scriptableObjectOne = scriptableObjectTwo) doesnt return error in my IDE nor Unity ? i swear that was not the case before i upgrade from Unity 2021 with VS 2019 to Unity 2022 with VS 2022
fucked me up twice this week, why is this happening, where is my error
using = in an if statement is a no=no, always has been
It's something from the asset store (https://assetstore.unity.com/packages/tools/animation/leantween-3595) but it's so easy to use, with a lot of tutorials and with a documentation. It's so helpful for animation movements and somethings like that. I'm doing my first game and using it is really helping a lot. You can also use .setOnComplete so when the animation is complete you can do a specific thing
yes thats why im asking, the error doesnt appear
it's not an error, it's just wrong
always has been ?, no red line under text ??
1 == 2 does not return a error, pretty close to that
there is nothing syntactically incorrect in using asignment in an if but it it is almost never what you want to do
That's not an error what you are making is to asign scriptableObjectOne = scriptableObjectTwo as you can do outside outside of the statement and checking if scriptableObjectOne it's true or not
that seems useful
well then i guess apparently i never made that mistake before, cause in my memory when i made such typo it wont run. good to know
I have a camera script that can rotate view, but when I do that, dragging with the mouse will keep following the original orientation forward and not follow the camera in the new direction it is facing - Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition); Vector3 move = new Vector3(offset.x * PanSpeed, 0, offset.y * PanSpeed); transform.Translate(move, Space.World);
If I set Space.Self instead, it will follow the direction correctly, but I can't find a way to lock the Y axis to stop the "zooming"
It gives you an error if the variable is something that it's not a condition, like
string hi = "hi";
if(hi=""){
}
But in case you use ScriptableObject, GameObject or something that can be null it will work since null is evaluated like false an any other value as true. I think it works this way
can you auto-set a layer mask from a script? Something like how you can auto add another script from a script if required. I'd like to automate this task to prevent me forgetting to set the right layermask
You can set it from script. Not sure what you mean by "auto-set"
Are you referring to assigning something in Awake/Start?
No. Just set it permanently in the editor. Should've specified that
Sure, custom editor
Permanently? What's the situation/use-case? I'm having difficulty understanding what the wanted feature is.
I'm making an interaction system, each interactable object is gonna have an Interactable() script with an IInteractable interface, and is gonna have to reside in the "Interactable" LayerMask. It's something i'll have to set manually each time in the editor and i'd like to avoid the chance of me forgetting in the future. I know i could set it in awake() but i'd like to know if there is a better way instead of changing it each time for each object
Place all interactable prefabs in a folder, mass select all of them, and set the layer . . .
what if they're not prefabs?
i mean i could do that yeah. just wanted to know if what i wanted to make was a possibility
Then auto-set the layer in code. I don't see what the problem is?
Onvalidate()
mhm?
As Invader said, just do it by code if you know, that its gonna be that case anyway
aight
A better way of changing it each time for an object is to use code, to do so automatically. That, or manually select all of them, typically, from a folder and set their layer . . .
Not sure what other way you think there is . . .
I get it yeah, i knew how to do this. Just wanted to know if I could do something like RequireComponent() that automatically adds a component in the editor
bro i'm literally just asking if it's possible, idk where you see me saying that i have another way
Well, you were asking about setting a layer, not adding a component. That's a totally different situation . . .
I guess the question has been answered 🙂 So there is no PreSetLayer or something. Just do it by code when you add/create the monobehaviour/object 🙂
I was making an example. Just nevermind, it's fine
guys ive been getting this error a lot lately ive never got it before yesterday
the script is not that complex
Did you make sure, there are no compile errors?
It happens when the name of the script file is different from the main class name
Youve probably renamed the script, where it first had a space in the file name
Did you make sure there are no errors and that the file name and class name match?
what do you mean file name and class match
If FollowPlayer does not get called FollowPlayer.cs as filename, it wont work
The file name is the name of the file. The class name is the name of the class . . .
You can't have a space in the name
The complexity of the script isn't relevant