#💻┃code-beginner
1 messages · Page 496 of 1
stop saying words
also assembly is vauge
like assembly for a x86 vs for a old console, or for a arm or risc is entirely different complexity and instruction set wise
Assembly isn't that hard
blocked
I mean it's just a few flags, some registers and instructions that do things 😂
its more work but spec wise there is much less to learn then say C#
The universe is only made of a few elementary particles. How complicated could it be?
also there is no point since all it does is creates lots and lots of work
and then if you want to target a other platform you have to write yet more of it
also a good compiler will output more optmized code then you will write in asm
Yes of course, you have a set of elementary stuff that lets you do a lot of things 😂
Reading it without comments is awful tho
if it works in the tutorial and not for you, you missed something, did something wrong, or haven't gotten to a part where it works yet.
also would remove the try catch infavor of doing a double.TryParse
that way you can properly handle both outcomes of the parse and not mask other potential errors
Also ButtonTap is never called and everything is public which makes it harder to tell what parts are supposed to be purely handled in this logic vs called from elsewhere
What does unity consider as "Long life code"?
will need context for that question
At their last announcement thing they said they want to increase compilation speed by not compiling the core and "Long life code" so Im asking what they would refer to with that
ah
I'm having a silly maths problem.
I have a value range of 14 - 100 but I need those values to be 'remapped' to 0-100. How can I do that?
so what that means is say you have a library full of tools you added at the start of the project and very rarely modify
those will not be recompiled when other thigns change
So any dll/lib file I import then?
nah dlls never get recompiled since that was manually done before hand
this is for AssemblyDefinations
so ones you define yourself or code in packages etc
So kinda like #pragma once in cpp?
little smarter then that but similar idea
okay thanks
like for example in my project i have a NPC behaviour editor i made
i made it over a year ago and it rarely every gets modified, but is a ton of code
in the new unity because i have that in its own AsmDef it would not recompile that assembly becuase i changed other code
That's not the AI fault
This is the issue with copying code in general
You have no idea what it does if you never wrote it, and as a beginner you can't read it either
Thank ye.
I HAVE COMPLETED THE 1ST MISSION
!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.
hey guys im having an issue where its returning error because the nameText variable is null, any ideas? this is the object structure https://gdl.space/bulasehapa.cs
wait nvm turns out i needed to use TMP_Text instead of UGUI
yeah you're using the 3D world space text version
TMP_Text works for both
that makes sense
quickie here
what's the difference between | and ||?
let's say, i want to check if variable fruit is apple or orange
then you use two
one is bitwise or the other os boolean or
and if it's either apple or orange, return true
use || for booleans
Very rarely you need to do bitwise operations and if you don't even know what they mean, you should stick to ||
| still works on bool, but its short circuit logic differs would 90% use || unless its like bitwise logic on a enum
So this:
if (axisHandler = xAxisHandler || axisHandler = zAxisHandler){
}
reads alright?
two equal signs...
oh shit
yeah
In some cases using bitwise for booleans may make sense (when you want to execute both sides regardless) but even then it would be bad for readability and therefore using a different solution would be highly suggested
in that case i would still rather execute both, get the returns then do the condition
much more clear intent
Yeah, not good for readability
i have only used those operators for bitwise stuff
which does come up a decent amount of time
same
Assuming you aren't doing any bit operations, they would behave like..
Logical OR (|):
The | operator computes the logical OR of its operands. The result of x | y is true if either x or y evaluates to true. Otherwise, the result is false.
The | operator always evaluates both operands. When the left-hand operand evaluates to true, the operation result is true regardless of the value of the right-hand operand. However, even then, the right-hand operand is evaluated.
Conditional Logical OR (||):
The conditional logical OR operator ||, also known as the "short-circuiting" logical OR operator, computes the logical OR of its operands. The result of x || y is true if either x or y evaluates to true. Otherwise, the result is false. If x evaluates to true, y isn't evaluated.
That's a bit of a better explanation, thank you
I'm sure there's a case for it, but i can't picture it right now
why would i ever need to do a bit operation within unity?
flag enums
GizmoType.Selected | GizmoType.Active | GizmoType.NonSelected gives me a enum value that has all 3 of these bits set
var isSelected = (gizmoType & (GizmoType.Selected | GizmoType.Active)) != 0;
on the flip side this is true, if either of these bits is set
Try locking a Rigidbody's rotation on X and Z in code without it
keep in mind not all enums do this, only enums meant to be used as flag enums, where there are not overlapping bits betwene values
can do the same on any int type as well (byte, sbyte, int, uint, long, ulong, etc)
Mathf.InverseLerp + Lerp
yeah InverseLerp will get you to 0 to 1 range
Yeah I got it sorted, thank you 🙂
then lerp can go from 0 to 1 to any range you want
So, something a bit more specific
This is really close to the behavior i want
But instead of dragging the cube, i should be dragging the handle, i moved the code to the cube itself
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this is the code btw
My initial thought on how to fix this is to try and calculate the distance between the handler and the cube at first frame
and offset that at update if it's being dragged
went through thrice, I have written stuff ditto right and code isn't placed wrong
but i'm not entirely sure that's the best approach
What isn't working about it, what's the code, and what's the tutorial
what is calling the code
the code you posted just as it as a public method and nothing in that script ever calls it from a message like awake or update so must be called externally
That should fix it though
^ Cache offset on mouse down, add that offset to your final position, profit
making a simple calculator using unity on YouTube by GAW
all the buttons 0-9 and operators
Okay, and the first two bits of information I asked for?
so break thigns down, add breakpoints or logs and find the exact flow
also get rid of that try/catch its just going to hide issues
with try and catch, the code gives invalid at every inputs
when I remove it, gives the error "cannot convert dbnull into double"
Hello. I'm trying to set up an interface for a sprinting action in my project but the coroutines I established seem to be resetting the value instead of gradually increasing and reducing the stamina value according to the conditions I set.
Link is here:
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yes I caught on that I have remove it
yes, do like a if (double.TryParse(mystring, out var myNumber)) { instead
i have kept the result as a double 0.0, changes to my values
do you mean inputfield I use as string?
at the point you are trying to parse a string into a double
ok so the input
You're starting a coroutine inside a while loop. That means you're going to start infinity coroutines until your stamina hits zero, then all of the coroutines you started will stop
if you use the TryParse instead of getting a exception on failure, you can just branch in a if statement.
the try/catch is very bad since its a very broad exception you are checking for, so if literally anything goes wrong it will do the catch, even if unrelated. that will hide error logs
Each instance of the DecreaseStamina coroutine is going to hit a single subtract call before hitting their yield, and that's the only reason this code doesn't crash unity
Well. How can I keep decrease stamina active while the button left shift is held?
Probably by checking if left shift is held in Update, and subtracting some small amount of stamina each frame
first detect input, and if its held down, then on all frames its held down decrease stamina, would also scale it by delta time so its not depednent on the framerate
I have put the Running() method in update
Remember, a while loop runs to completion. Once a while loop starts, nothing else in the entire program can occur until it finishes. The yield in a coroutine "pauses" the loop for a moment, but Running is not a coroutine. That while loop is going to do absolutely nothing else in the entire program until stamina is 0
No new frames can render. No objects can visually change. No other objects can run any code at all
until Stamina hits 0
why is tryparse hiding erro
error
its not, the Try/Catch is that you were using
public void ans()
{
if (double.TryParse(CurInput, out answer))
{
answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
CurInput=answer.ToString();
UpdateDisplay();
}
else
{
CurInput="invalid";
UpdateDisplay();
}
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}
printed invalid on 9+1(i may or may not have used in incorrectly)
also you are not even trying to undertstand things, you no longer need the System.Convert.ToDouble since the double.TryParse does it for you
If CurInput is something that can be parsed in a double, it'll do the first chunk. Otherwise, it'll set CurInput to "invalid" and update the display. For what it's worth, the word "invalid" is also not a valid double
Is CurInput the string "9+1" because that's not a double and it is properly reporting it as invalid
i have an Array with a non specified size. If i do myNoSizeArray = otherArray, its going to copy size and the data, right?
What commands can I use to subtract variables by frame?
No, if you do that then both array variables are referencing the same array
It's going to have both myNoSizeArray and otherArray referencing the same data
yes, i am trying to use System.Data.DataTable().Compute because i am trying to make something not have multiple if statements for each operator
no its just going to assing myNoSizeArray to otherArray
myNoSizeArray will still exist if youj have a other reference to it
no reference types dont create deep copies like that, its the same object
Then you need to compute first. The formula itself is not a double
I like how we gave the same answer in 4 different ways
If you subtract a value in Update, it's going to subtract that value every frame
so they both will have same data from otherArray?
They will both be the same array
they will both be the same array
its literally pointing to the same object in memory
They will be two different variables holding a reference to the same array
no data copy has taken place, you just end up having mySizeArray point to the same data as otherArray
ok
so if you modify one, they both get modifed in this case
since they are the same object in memory
If you did this:
myNoSizeArray = otherArray;
myNoSizeArray[0] = "Fungus Amogus"
Debug.Log(otherArray[0]);
The output would be "Fungus Amogus"
if you want a copy then you need to make a new array with same size and copy over data (if the items in the array are also reference types you need to cerate a new obj for each one or you're just putting the same objects)
what an example
made me shed a tear
ahh there has to be a way to do this right? or at least achieve something to the same effect?
just create the array awake or something
If you want to use variables in a initializer they should be const or static
i am super new to unity i only know till input.getkey(keycode) and input.GetMouseButtonDown() sry
yeah you can def do that too, you just won't be able to ever change them outside of code / initilizer (in the inspector for example)
All of the stuff outside of a function is going to run at creation time. Thise variables don't actually have any data yet at the time that array initializer is run. You'd need to do it in a function so all those variables are guaranteed to exist by then
also, this error confuses me as if it doesnt convert, why does it work on the tutorial? is there s library im missing?
currentl impoted system.data
can you show which line this is throwing, hard to say without context
Whatever DBNull is, it can't be cast to anything else
public class Clac : MonoBehaviour
{
public TextMeshProUGUI disptext;
private string CurInput="";
private double answer;
public void ButtonTap(string val)
{
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
CurInput=val;
UpdateDisplay();
}
}
public void ans()
{
answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
CurInput=answer.ToString();
UpdateDisplay();
if (double.TryParse(CurInput,out answer))
{}
else
{
CurInput="invalid";
UpdateDisplay();
}
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}
What is Clac.cs line 18
that doesnt show what nvmDBNull is and what ur trying
public void ans
which runs answer=system.data.whateverthelongcode
Then you probably need to save your script and try again to get the actual line number
please send the full code without omitting the namespaces
saved alr
i have
no you sent it without the namespaces, the lines dont match up
qsfdgh
oh
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class Clac : MonoBehaviour
{
public TextMeshProUGUI disptext;
private string CurInput="";
private double answer;
public void ButtonTap(string val)
{
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
CurInput=val;
UpdateDisplay();
}
}
public void ans()
{
answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
CurInput=answer.ToString();
UpdateDisplay();
if (double.TryParse(CurInput,out answer))
{}
else
{
CurInput="invalid";
UpdateDisplay();
}
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}
wait
Should probably check if Compute returns a DBNull or not
wheres my namespace
its fine now but 18 is open bracket for some reason so 🤷♂️
added it
You could use a Linq query.
playerOwnedAccessories.Where(acc => acc.player == playerToLookFor).FirstOrDefault()
It'll check each element, store it in the temporary variable acc, and if that acc's player is equal to playerToLookFor, it'll retrieve it. FirstOrDefault will ensure you get exactly one answer, or null if there are none.
How about post the !code properly to a bin so there's line numbers
📃 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.
yeah but idk your error seems different than the file you sent..
System.DBNull.System.IConvertible.ToDouble (System.IFormatProvider provider) (at <8ce0bd04a7a04b4b9395538239d3fdd8>:0)
System.Convert.ToDouble (System.Object value) (at <8ce0bd04a7a04b4b9395538239d3fdd8>:0)
Clac.ans () (at Assets/Clac.cs:34)
Clac.ButtonTap (System.String val) (at Assets/Clac.cs:18)
UnityEngine.Events.InvokableCall`1[T1].Invoke (T1 args0) (at <54724222b7684530a2810ae1eac94ec7>:0)
UnityEngine.Events.CachedInvokableCall`1[T].Invoke (System.Object[] args) (at <54724222b7684530a2810ae1eac94ec7>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <54724222b7684530a2810ae1eac94ec7>:0)
UnityEngine.UI.Button.Press () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:530)
mine lands on open bracket, make sure you saved and run the code again
Is there anyone that help me with coding a script that allows me to hold a button and freemove the camera with my mouse, but when I let go of the button, snap back to defaults?
There we go, line 34. Now post the code properly so we can see what that is
is it something during instaallation
of unity
how do i do that
No, none of this is Unity's fault
no lol you're just sending a different version than what error printed
screenshot?
Read the bot message I called up
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
i used that in all of the boxes
DataTable.Compute returns DBNull.Value if it fails
ohhhhhhhhh
omg ty
what?
yes you formatted the code but you were sending an entire class and people can't see lines unless they paste in IDE, thats inconvenient. Use the paste websites
What is wrong with what I posted?
And you are trying to convert it into a double
you posted in a code channel, at very least post the code..
You didn't have an actual question in there. What is the specific problem you're trying to solve, what have you done, what isn't working
I don't have the code - I need help coding it to begin with. I checked the Unity documentation and am not sure where to go with it.
how do i send the hatebin link,
Ctrl+V
!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.
If it doesn't give you a URL, use one of the others
https://gdl.space/ujubiwacun.cs https://gdl.space/aqumugixah.cs why does the public var thingy doesnt work
What "doesn't work"
something with the varibles with t
it using in other scripts
What
idk it doesnt work the varbles arent working
11234 this is my error floo
what doesn't work
Okay, line 34 is still nothing with code on it. Save the script, run it again. Don't change the script after getting the error and posting it
Debug.LogError("NPCInteractie script not found!");
} i get this
but why idk
Are you still trying to use a data table?
i use if statements like that
Okay, good. Finally. That means npcInteractie is null. Where do you set it
im just trying to see the problem there, your suggestion worked so my assignment is done
thanks
on start?
Where?
the problem is your datatable is empty and Compute works on the rows in the datatable as per the documentation I linked to you
in the start from ItemInteractie
Show the line that sets npcInteractie
public void npcInteractie()
{
if (level == 0)
{
level = 1;
Debug.Log("ga naar de item");
Canvas1.gameObject.SetActive(true);
Debug.Log("je bent nu level 1");
itemInteractie.cangetitem = true; // hier gaat wat fout
}
}
my bad, the error is on line 36
📃 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.
This is irrelevant
This is a function named npcInteractie on a different object
I'm asking you
where do you set the variable
on the object that is giving the error
NPCInteractie [SerializeField] ItemInteractie itemInteractie;
Okay, good. Your issue is that CurInput does not evaluate to a result from new System.Data.DataTable().Compute so it returns null, which is not a double
never mind i didnt add my Serelized field
That is where you create the variable. Where do you set the variable
Welp, that didn't work too well
Could someone explain why this coroutine freezes my game for a split second when called to activate a very simple UI? I've narrowed it down to the UI being the issue, but it makes no sense why it would be. The UI in subject:
are datatables complex?
Whenever any object on a Canvas is changed (including enabled/disabled), the entire canvas repaints. If this is a small panel on a complex UI, it'll take a while to repaint the entire UI
Have you checked the profiler?
not at all, a datatable comprises of DataColumns and DataRows
public class MouseLook : MonoBehaviour
{
private Vector2 Move;
private Vector2 Look;
public float mouseSens;
public Transform playerBody;
float lookx;
// Update is called once per frame
void Update()
{
lookx = (Look.x * mouseSens * Time.deltaTime);
playerBody.Rotate(lookx * Vector3.up);
}
public void OnLook(InputValue value)
{
Look = value.Get<Vector2>();
}
}```
I know that, but if I enable/disable it without the coroutine it doesn't lag (it's not a complex Canvas)
Also I did check the profiler @wintry quarry, and it spiked from scripts, when called the coroutine to activate the UI.
Why ping me without showing what you tried etc.
use it at the bottom too
turning is very slow and stilted and remains same speed no matter spead of mouse
which scripts? Check the particluar code that's doing it. If it's your code, you can optimize it
My bad, game recorder's not working too well for some reason, sorry
What calls ShowUIForSeconds
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Don't multiply mouse movement by deltaTime
It's already framerate independent
Yeah that could as well be Java
i'm adding it on update, so
Why's that?
C# is "Microsoft Java" after all
Huh
It was originally based off of java
E: Not technically, but syntax/design wise
I remember someone saying that a while back, but i don't quite understand what differentiates it
mainly because i don't know java.
still moving at the same speed even without deltatime
so i need to fill th datatable to use it?
how do i fix that
Back to the task at hand, transform.position is set to new pos, which is then added to axishandler offset, which changed the transformPosition, which becomes newPos, which is added to axisHandlerOffset, ad infinitum
Don't try to parse CurInputs that aren't Computable expressions?
Do you even know what CurInput is when it fails?
So i don't understand the course of action to stop that here
something like 0/0?
What is calling OnLook? What Input Action is that mapped to?
Is this a guess, or did you check what value it was when you got the error
Because you can just... check
you don't have to assume
how do i do that, i take 2+3 and the answer would compute but stops at dbnull, which is datatable
Log it
what
I got too much brain fog atm to give you the answer
Btw post the whole script
It could be fixable if you don't make the handles children of the cube
But then you'd have to redesign it a bit
Sorry it took me a bit to reply was cooking
Is this script on multiple objects? The hasNotepad bool should prevent it from running multiple times, but maybe a bunch of copies of this are running it at the same time?
there we are
No it isn't, and it serves a single small purpose and yet so hard to do for some reason
i feel its wrong, it should output "4+3"
What is the last log before the error occurs? You probably want to disable "collapse"
not having collapse makes my console miserable but here you go
Okay, assuming your log is right before the error, then it would seem 3 evaluates to DBNull
@polar acorn chagpt has no idea whats causing this either
ChatGPT has very very little clue of anything in general
Instead of using a composite binding, you want to use a normal binding. Composite bindings are for creating analog outputs out of digital, so it detects if any movement occurs, and treats that as "1". Your "Look" action should look similar to the MouseAim I have here. You can also add a composite for the keyboard, just don't use a composite for the mouse.
Can you show the profiler that's showing the spike? It should say what functions are taking up the time if you inspect it closer
Yeah will do that in a few mins
my data type was wrong all this time?
aye, thanks
but operators wont work in int or double
make a different string called operator and make a big mess of it?
messiah where are you
Man I hate how similar some of the colors on this are, but it looks like that spike is from Garbage Collection, not Scripts
I've disabled everything but the scripts when I first tested it and it spiked hard
It's one of the dark browns, and GC is the most likely one of the dark browns to suddenly take 266ms and then shoot back down
A single coroutine will produce some garbage, but it shouldn't produce that much
one sec
Why is it failing? The first command would convert 4+3 into double but isn't + can't be converted into double it would stay string right?
making it int(4) string "+" int(3)
I'm new so I might sound stupid as fk
but isn't that what compute does
you are not listening to a word I am saying, I've given you the answer twice already
Show the updated code, with your logs
Here's screenshot with everything but them 3 components enabled, it's the scripts
Because literally none of these throw errors.
as per my knowledge, static wouldn't effect right?
also, unity is taking these inputs as
4
+
3
which makes me think they aren't in the same string
Okay yep that definitely looks like scripts. Let's do a quick sanity check - the first line of your coroutine, add this line:
Debug.Log($"Coroutine started on object {gameObject.name}");
And check to see if it's showing up multiple times
Wait maybe this is the TextMeshPro empty character issue?
Just show the code
I tried that before, it's only once
Possible, now that you mention it. If the TMP text is an Input box's attached text
🤔 Okay that's odd. I have no idea why a single coroutine would be so resource intensive
i didnt drag anythn
Exactly
At this point I'm stumped. I dunno if anyone else can see anything I don't but I really don't see how this could be taking up so much time unless there's a lot of stuff on the canvas, or the coroutine's running multiple times, and it seems neither is the case?
Regarding your main issue, is the input string coming from a text object under a TMP input field?
It's just a raw TextMeshProUGUI, and not a child of an Input box?
Okay, then it's not the invisible character issue
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
namespace TheProj{
public class Clac : MonoBehaviour
{
public TextMeshProUGUI disptext;
private string CurInput="";
private double answer;
public void ButtonTap(string val)
{
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
CurInput=val;
UpdateDisplay();
}
Debug.Log(CurInput);
}
public void ans()
{
answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
CurInput=answer.ToString();
UpdateDisplay();
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}
}
regarding ur earlier req
You're logging CurInput after the error
I said to do it before
literally the line right before
the logs are worthless as they are. If there's an error, we won't see it
The stuff that was logging was the things that did work
its before error
No, it isn't
the error is at line 36, answer=system.convert.longessay
You see how the green circle is after the red circle
im dumb
Meaning if there is an error in ans, the log does not happen
this isnt log?
These are logging after the line that throws the error
meaning that it passed the problem and printed
so, by definition, these are the values that did not cause an error
you have to log before the error. Not after.
There's nothing on the canvas active when the coroutine gets called
Once an error occurs, the code stops
!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.
wait a second, where are you actually assembling the expression to evaluate?
ok i see
Yeah, I'm out of ideas at this point. I hereby grant you permission to repost this question in #archived-code-general or higher. Maybe someone else will notice something I haven't?
Thanks anyways for your help mate.
i see
as people have mentioned a long ass fuckin time ago
https://gdl.space/jayoficiri.cpp why does it not recognise any collisions please i dont get it i also tried a print() in the ontriggerenter and exit functions
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
CurInput=val;
UpdateDisplay();
}
val is a string on buttontap(string val)
public void
When val is "=", it runs ans which reads the value of CurInput, which is currently nothing
on no input that would be the case, or it would always be the case?
Hello, I am using this video as a basis for an npc tank in my game so it will move more like a vehicle
https://www.youtube.com/watch?v=mNoyPz3LCy0
But is there a way to impliment the navmesh with this movement so that it won't keep running into walls
✅ Get the Project files at https://unitycodemonkey.com/video.php?v=mNoyPz3LCy0
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🌍 Interesting Game Dev Videos https://www.youtube.com/playlist?list=PLzDRvYVwl53vD6I_5QE8jV-TYjckA7w_w
Here's the Racing RTS I made for ...
Link to source code: https://patreon.com/GameAssetWorld
🎮 Welcome to this Unity 2D Game Development Tutorial! In this step-by-step guide, we'll show you how to create a fully functional basic calculator using Unity, suitable for beginners and aspiring game developers.
Key Points Covered:
🔷 Setting up a new Unity 2D project.
🔷 Designing the c...
Compare
public void ButtonTap(string val)
{
Debug.Log(CurInput);
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
CurInput=val;
UpdateDisplay();
}
}
bro why you talking like 500 years ago
I possess a rigidbody and all requisite 3D colliders. Yet, I am at a loss regarding thine utterance, 'I shalt tick isTrigger.'
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 178
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-09-26
It's called a joke
+= was the issue
Did you tick the box
i was seeing this vid at 140
Yes. You were overwriting the command every time anything was input
even if it was null
instead of just adding empty to the running function
which would have left it unchanged
i wasted 4 hours because of video quality
Pray, what dost thou meaneth?
Okay, so, in computers, there's a thing called a checkbox
when you click it, it gets a ✅ in it
did you do that
he is telling you how to fix your problem
Verily, I dost believe so.
AKA click the Istrigger box
Okay, show the inspectors of both objects
whys the error still there after save
What's the log say the value is when it errors
So, this would probably be why the tutorial had try-catch but it's a bad tutorial anyway and you shouldn't do that. Instead just check to make sure the length of CurInput is greater than 0 before running the stuff in ans
If its length is 0, don't do the calculation
Pray, my noble squire, cast not thine judgments upon me, yet I confess, I hath overlooked the need for a rigidbody upon my terrain.
curinput is privae
private, woudl it still show in debug.log
Then maybe you should have fuckin read the answer I gave instead of being a dick about it
You've literally been logging it the entire time
If private were a problem it wouldn't compile
ok chill bro im sry
whys it debugging when i click twice
theres no answer btw it still says cant convert into null
What is the log before the error
guys im still getting that jittering we fixed yesterday ( but actually i think this a bit of jittering was there yesterday too, I didn't change anything with script, only changed sprite which has nothing to do with it)
Script is in fixedUpdate
//Player Rotate Follows Mouse.---------------------------------------------------------------
if (PlayerRotates)
{
//Debug.Log("Should rotate");
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 lookDir = mousePos - transform.position;
rb.rotation = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 270;
}
Vector3 moveDir = new Vector3(moveX, moveY, 0f).normalized;
Vector2 targetVelocity = moveDir * speed; // your movedirection * speed
Vector2 velocityDiff = targetVelocity - rb.velocity;
rb.AddForce(velocityDiff * acceleration);
However if I turn off rotation script and try to rotate the other way (rotation doesn't work neither in fixed or normal update) but jittering stops
As a test, disable your camera movement so that it stays still. See if the character still jitters
Please help! I have a two scene game where the audio player is important to the game working. It works fine when I run the game starting in the gameplay scene and have the audio source placed via inspector. But if I start the game from the menu, the game objects lose the reference to the audio source and this doesn't seem to work.
In this case character stops jittering
What if you use MoveRotation instead of rotation
empty (clicked 4 once)
4 (clicked 4 twice)
Oh so with "rotate the other way" you mean moverotation
//Player Rotate Follows Mouse.---------------------------------------------------------------
if (PlayerRotates)
{
//Debug.Log("Should rotate");
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 lookDir = mousePos - transform.position;
//rb.rotation = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 270;
rb.MoveRotation(Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 270);
//transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}
Did you add in the length check I suggested
This is current script which stops jittering but stops character rotation aswell
//rb.rotation = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 270;
if I use this rotation works but it jitters
see my references (ignore the warning, it was because i misused a text)
Open rigidbody constraints, you don't have rotation constrained do you?
onclick() and disptext in clac input
The "Constraints" tab in your rigidbody's inspector
Did that
this is for tmp
Yeah lol your rotation is frozen
oh shit
wait I did that because of something as I remember
but wait i'll try
wow
Smooth! thanks.
I realise I was asking this in the middle of another thing lol but if that's solved I'd really appreciate help here
Okay cool
@wintry quarry It seems like rb2d.rotation does break interpolation after all
The reason that MoveRotation didn't work was because the rotation was constrained
Oh I see so we know that too now
so instead of using rb.rotation I should use moverotation() to not break interpolation
I was always under that impression
The 3D rigidbody.rotation doc says:
If you want to continuously rotate a rigidbody use MoveRotation instead, which takes interpolation into account.
While the 2D doc doesn't say much
@lofty lintel Could you quickly switch back to rb.rotation but keep it unconstrained
And see if it still jitters
ok i'll check
Yes it jitters using rb.rotation especially when I rotate the player (which makes sense)
wait how do I write code like this
Alright then we can safely say that rb.rotation breaks interpolation
Surround with two of these ` on each side
does rb.velocity break interpolation too?
Nope, that's fine
afaik no
oh that's good
no im using that
Only rb.rotation, rb.position and ofc transform.position/rotation which you shouldn't ever use with rigidbodies
how do i add that? by making CurInput=val? or making it = a value
i mean i could see why using rb.rotation would break interpolation because you are setting the rotation manually
same as transform.position
you would most likely use moverotation
i think you mean rb.rotation instead of rb.velocity
yes
Oops yeah, edited
keep in mind some things apply in 2D than 3D because they use a different physics engine
now that digiholic died(rip), im now gonna cry
what?
he has a life lmao
be patient
ik bro i was just coping
TLDR; I'm trying to make it so my car won't be able to turn if he is not moving or forward but my code didn't work.
my main objective here is not to primaly understand why this code did not work for learning purposes
I thought of making the car be unable to turn while he is not moving back or forward so i thought that making it so that
(if the car isn't receiving forward or back input, then his horizontal Input will be zero).
I made a if statement with that logic and placed it in update to make it happen every frame.
Since my car rotation value is multiplied by horizontal input, i thought making it zero would multiply with everything there and make it all zero, nullifying any rotation.
As you can see in the video, it didn't work (i made sure to save the code befor testing it).
Why didn't that work? what did i miss?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
//Private variables
public float speed = 20.0f;
public float turnSpeed = 45.0f;
public float horizontalInput;
public float forwardInput;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (forwardInput == 0)
{
horizontalInput = 0;
}
// here, we get the player's Input
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
//we'll move the vehicle forward based on vertical input
transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
//we'll rotate the vehicle based on horizontal Input
transform.Rotate(Vector3.up * Time.deltaTime * turnSpeed * horizontalInput);
}
}
You should also multiply your rotation with the Absolute value of forwardInput
im a beginner too but with my primitive brain I would just detect if its moving and rotate it only when moving
Or just make it zero when forwardinput is near zero
Oh ok I see you tried that here:cs if (forwardInput == 0) { horizontalInput = 0; }
But you should do that after setting it to the input value
Also GetAxis has some smoothing by default so it might take a small while to reach 0
yeah, so my main goal isn't even trying to find other ways to make it work, but to understand: why didn't this aproach worked? what did i miss?
Wait is this from the Unity Learn site?
The one lesson where they teach you to use transform to move a rigidbody? 🤦♂️
yes
is that bad?
yes as it will ignore collisions
Yes, shame on whoever wrote that
and pretty much everything with the RB
Hey guys, can you build and run a project that has a database to your phone?
You might miss collisions entirely
I've learnt that too like months ago before dropping unity xd
wait... but the collisions to the ground and the boxes seems to have worked fine...?
i'm confused
confused on the datatable one
Well I just sort of explained it, but the if statement that you used to set horizontalInput to zero doesn't do anything since you changed horizontalInput after it
it works with console.writeline?
if you go forward into a wall it should ignore collisions
transform doesn't always ignore collisions, it's just not reliable
It might seemingly work fine in a small demo like this, but them teaching it on the unity learn site is just awful
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
namespace TheProj
{
public class Clac : MonoBehaviour
{
public TextMeshProUGUI disptext;
private string CurInput="";
private double answer;
public void ButtonTap(string val)
{
CurInput+=val;
Debug.Log(CurInput);
if(val== "=")
{
Debug.Log(answer);
}
else if(val== "C")
{
Clear();
}
else
{
UpdateDisplay();
}
}
public void ans()
{
answer = System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput, ""));
CurInput = answer.ToString();
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}
}
i placed that at the bottom of my update and it didn't change the result...
That's also wrong, at the bottom of the update you have already rotated the car
You should do it after the Input lines, but before rotating the car
the debug is for checking errors
Code executes from top to bottom
Are you trying to parse an expression thatis just "="?
IT WORKED!!!!!!
THANK YOU!!!
its supposed to compute "1+3" when i hit =
i changed it to debug the log of answer, which computes the string
im dying
Seems like you still add the = when you hit it, so you pass 1 + 3 = to the DataTable which is obviously invalid
updated code btw
so i remove on button click for =?
If the main website of the engine is teaching me to work with it in the wrong way....
then what should i do? What is the right or good aproach that would be expected of me in a work enviroment?
No, you do not add the = to the string when you receive it
so, how do i make = onnly execute the code?
use the rigidbodies methods so Addforce,Velocity,moverotation,etc
usually you shouldnt use the RB transforms due to inacurate collision detections
but for something small, i believe your okay
I'd like to believe that mistakes like this are rare in the Unity Learn site, but I can't say for sure.
I mostly learned by:
-Trial and error
-Reading documentation
-Googling my issues, a lot of them are answered in the unity forums
Just like I told you, do not do CurInput += val; if you're not certain you'll execute UpdateDisplay().
This means that you need to move that line in the else so it only executes when you type a number or an operator (and not an = or a C, because yes it'll add the C at the end of the expression too!)
but i have to say, its refreshing for a beginner to want to learn so thank you 😁
thats what i did earlier, but it was causing it to not give any output in debug.log(CurInput)
failure is the only way to learn so everything you said is very true
thank you to both Osmal and dec_ves for explaining that to me.
I kind of suck when it comes to know what to look for when learning to code and this is the type of stuff it could take my a LONG time until i discover, if ever.
causing the error(cant convert dbnull into double)
ello
well thank you for being a good sport, and if you need help feel free to ask and you will get used to it eventually everyone starts somewhere
Your expression failed to compute or was empty. Log it before trying to evaluate it using the datatable
yes, its empty in beginning and changes value when val(onbuttonclick) is used by [0-9]
or when +,-,/ and * is used
Prove it with a log, right before you do new DataTable().Compute(...)
do i simply declare it as a string without value?
thank you for taking your time to teach me!
I have a ton more doubts but i think they are too ambitious for me to understand at the moment.
That said, would it be okay for me to continue to learn using the Unity learn course?
So far it is the best guided course i found...
for sure, if you have any more questions about it, ask away
i type 1+4
namespace TheProj
{
public class Clac : MonoBehaviour
{
public TextMeshProUGUI disptext;
private string CurInput="";
private double answer;
public void ButtonTap(string val)
{
Debug.Log(CurInput);
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
CurInput+=val;
UpdateDisplay();
}
}
public void ans()
{
answer = System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput, ""));
CurInput = answer.ToString();
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}
}
There you go, your inputs aren't registered into the string
remember to use the documentation for it as well !docs
string is val, buttons have refernce to clac.buttontap
inputs would register into val and change curinput
but curinput doesntchange
Debug further. Log the value and the Length of val, make sure the else part is even executed
curinput
val
oh no.
need help yall yo
Check the length of it. With an if statement. Why would setting it to a different value have anything to do with checking length?
what exactly does length mean?
The length of a string is the number of characters in the string
how does an if statement give length
you get the length, then you check its value to see if its something
the result of that is a bool which is what an if statement is for
Well... After doing a tuto to allow my character to respawn, I noticied that sometime my character respawned into the ground. After checking the comments section, I found out that i needed to to have the "Player" object deactivated when entering inside the DeathZone and then reactivate it with a Coroutine, but the one who gave that solution forgot how they did that, so I tried by creating a boolean variable with a script for activating Player. Here's the tuto in question (in French) and the current states of both the Player Activation and Deathzone scripts: https://youtu.be/5MmX3Mea29Y https://hastebin.com/share/agivupigur.csharp
https://hastebin.com/share/aweraticos.csharp
Aujourd'hui on regarde comment ajouter des zones d'élimination dans nos niveaux. Cela nous permet notamment d'éliminer le joueur s'il tombe dans le vide ou se rend dans une zone inaccessible.
☕ Soutenir la chaîne ☕
➡️ sur Tipeee : https://www.tipeee.com/tuto-unity-fr
➡️ sur uTip : http://utip.io/tutounityfr
📥 Télécharger le projet de la série ...
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Running this in my code and I get these errors that it doesn't exist
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
[RequireComponent(typeof(CharacterController), typeof(Animator))]
public class CharacterHandler : MonoBehaviour
{
CharacterController characterController;
private Animator animator;
[SerializeField]
private float movementSpeed, rotationSpeed, jumpSpeed, gravity;
private Vector3 movementDirection = Vector3.zero;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Vector3 inputMovement = transform.forward * movementSpeed * Input.GetAxisRaw("Vertical");
characterController.Move(inputMovement * Time.deltaTime);
transform.Rotate(Vector3.up * Input.GetAxisRaw("Horizontal") * rotationSpeed);
if(Input.GetButton("Jump") && characterController.isGrounded)
{
movementDirection.y = jumpSpeed;
}
movementDirection.y -= gravity * Time.deltaTime;
characterController.Move(movementDirection * Time.deltaTime);
//animations
animator.SetBool("isRunning", Input.GetAxisRaw("Vertical") != 0);
animator.SetBool("isJumping", !characterController.isGrounded);
}
}
It won't swap animations even though movement and everything else works
It's case sensitive
Do you happen to know how I can make an animation end the moment the transition starts?
or make it faster at least
Guys how would I reach all of those in loop
(like inside code)
float min = StickUiParent.Find("Spawn").position.x - 9f;
float max = StickUiParent.Find("Spawn").position.x + 9f;
float randomPos = Random.Range(min, max);
if (LastPos.IsUnityNull())
{
LastPos = new Vector3(
Random.Range(StickUiParent.Find("Spawn").position.x - 9f,
StickUiParent.Find("Spawn").position.x + 9f),
Random.Range(StickUiParent.Find("Spawn").position.y - 1f,
StickUiParent.Find("Spawn").position.y + 1f), 1);
}
else
{
//StickUiParent.Find()
//while (randomPos >= LastPos.x - 0.4f || randomPos <= LastPos.x + 0.4f)
//{
// randomPos = Random.Range(min, max);
// if (randomPos <= LastPos.x - 0.4f || randomPos >= LastPos.x + 0.4f) break;
//}
LastPos = new Vector3(
randomPos,
Random.Range(StickUiParent.Find("Spawn").position.y - 1f,
StickUiParent.Find("Spawn").position.y + 1f), 1);
}```
Basically what im trying to do is that when I initialize them in position I don't want any of them to be like too close to each other. I want them to be aligned with a bit of distance.
And second question is what I asked in [#📲┃ui-ux](/guild/489222168727519232/channel/502171135350407168/) so basically how do I move stoneUIs behind that brown UI (im confused since they don't have order in layers.)
Turn off exit time
set the transition speed to 0 w/ no exit time
One approach I started is using tags on StickUI prefabs.
bruh lol when length=<0
stop using GameObject.Find.
Start learning to use arrays.
or using transform.GetChild(n)
Where may I find this?
maybe a weirdo question, but i want to make a script that only exists to do one thing, and will only ever be called for that one purpose. I want ohter scripts to be able to call functions in this script. How would i approach this?
don't see it anywhere
click the transition arrow
Oh
That's how all your scripts should be ideally. What part is confusing you?
Thanks, I appreciate you guys
I do know how to work with arrays in c#, but im trying to get like array of those StickUIs
does transform have GetChildren?
hm, i have a script on an empty object, but how do i reference the outside "helper" script? do i also put on the object?
it has childCount and GetChild
so you can use it in a loop
Also why not just put them in an array in the inspector though
Yeah but it takes index I don't want that
they spawn later on in hierachy
That depends on how you want it to work. Is it associated with that object?
Add them to a list as you spawn them,
then you have the list at all times
No not at all, the "helper" script organizes a bunch of data, for the "main" scripts to use.
for (int i = 0; i < transform.childCount; i++) {
Transform child = transform.GetChild(i);
}```
public GameObject StickUI;
public Transform StickUiParent;
public GameObject StoneUI;
public Transform StoneUiParent;```
if you want
up to you man
alright i'll try.
what kind of data
"global data"?
Make a singleton
oh this does make sense but only one problem I have with that is that I have spawn object inside that too so it will count as child.
Nah i want to send a list to the helper script, and get back a messed up version of that list
alright yeah im giving up on unity
spawn thjat object separately. Make the hierarchy clearner. Make one container object just for these things.
Or, better yet, as I mentioned, just keep the things in a List as you spawn them like I said before
ive asked the solution of an error for 9 hours for no solution lol
StickUIs.Add(Instantiate(StickUI, LastPos, Quaternion.identity, StickUiParent));```
This would work well right?
Maybe you just want a static method? You're being really vague
yes
I can't seem to jump on my character. Not sure if it's to do with how unity handles IsGrounded or not with the CharacterController. I can't seem to find where you can check if you're grounded or not
then spend more
switching engines wont fix your problems there will be new errors there, if you decide to switch
I'm gonna be honest, i literally just dont know how to reference another script while im in one script. Do i need to have a component or does calling it just "create" it?
who said im switching
No errors, but spacebar won't work
https://gyazo.com/b3943acb16f4d219abd5fd228b87299e
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
[RequireComponent(typeof(CharacterController), typeof(Animator))]
public class CharacterHandler : MonoBehaviour
{
CharacterController characterController;
private Animator animator;
[SerializeField]
private float movementSpeed, rotationSpeed, jumpSpeed, gravity;
private Vector3 movementDirection = Vector3.zero;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Vector3 inputMovement = transform.forward * movementSpeed * Input.GetAxisRaw("Vertical");
characterController.Move(inputMovement * Time.deltaTime);
transform.Rotate(Vector3.up * Input.GetAxisRaw("Horizontal") * rotationSpeed);
if(Input.GetButton("Jump"))
{
movementDirection.y = jumpSpeed;
}
movementDirection.y -= gravity * Time.deltaTime;
characterController.Move(movementDirection * Time.deltaTime);
//animations
animator.SetBool("IsRunning", Input.GetAxisRaw("Vertical") != 0);
animator.SetBool("IsJumping", !characterController.isGrounded);
}
}
ah yeah sorry my bad, i forgot you dont know the concept of an "if statement" so you wont know the word "if" either
There are many ways. No "calling it" does not create it
It depends on the circumstance
you should go through !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I am not sure if jumping is part of the character controller by default
ow
None of this is unity specific by the way. You might as well ask in the C# discord
I have it setup in the code. I think it has to do with the isGrounded
Then please show your code
Right here
can you not use the new input system and name it as such?
its part of the input system if im not wrong, so it is a button
GetButton takes a string, if you wanna use KeyCodes then use GetKey
oh shoot
thought that was the old one
he must not have it set up in the input system
I think the issue is grounded
Cause the rig will jump right at the start of the game
but can't use it again
Also I think "Jump" is defined by default
https://docs.unity3d.com/560/Documentation/uploads/Main/InputAxis.png
yeah, just figuring out C# syntax atm
used to lua
The issue is in regards to grounded
I removed it and I can jump, but not sure how to fix this issue. Is there a place I can check if IsGrounded is true or not
the built in character controller grounded works as it should
its integrated into it
Yeah, I think the issue is with my rig
that's what I'm thinking
does your character lift off the ground at all or just not play the animation?
like the height/scale
one sec, I'll check
but you can do your own grounded function as well by doing a raycast
spherecast etc
if (!condition)
keep in mind the character controller itself has to touch the floor
so if your model is suspending it, it will not work
How would I get this without find() or why is find() a bad practice?
put the center Y to 0
Again, store them in a list, or iterate over the children of StickPlacer
Find is extremely slow
and finicky
what are you asking?
try changing skin width
i just got other idea so I'll do it and ask in the end if it was a good practice like that, also I am kind of forced to use while loop...
to what? Don't see any changes in it. Lower or higher?
just mess with it
You are never forced to use a while loop
for and while can both be used for anything
thanks, that was it
if skin width is to small/big it messes with it
It was oddly too much
glad we were able to fix it
had to reduce it to 0.03
It doesn't. It's a property on the string:
string s = "Hello!";
Debug.Log(s.Length); // prints 6 to the console
appreciate the help man
yeah makes sense
I oddly can't jump while standing still, but can while moving. Is there a reason for that?
yall thank you for troubling urself for helpin but im too sleepy to continue coding, its like 5 am i havent slept
3 days in a row im dyin but really appreciate yall sticking oout
How long something is
not sure why it would be doing that you can try to either mess with skin width again or use you own grounded boolean
other than that, im not sure why since you have nothing checking if you can jump other than the keycode
Ah it was the center needing to be lowered
how i can make my dino jump like in the real game ? i have tried with constant force but idk if it look good.
and yes as Osmal said if you make your skin width to low it will get stuck
is there a task wait in C sharp I can use or a coroutine to delay my jump? Or can I setup an animation event to listen for somehow?
thanks
Reason for this is it's kind of a charge jump
Raise the gravity and jump force
would be an easy way to speed it up
you can use a coroutine or invoking it to delay a jump
try invoking it first
this is not lua
invoking a method ~= calling a method
looks like my logic didn't work after all.
float minX = StickSpawn.position.x - 9f;
float maxX = StickSpawn.position.x + 9f;
float minY = StickSpawn.position.y - 1f;
float maxY = StickSpawn.position.y + 1f;
float randomXPos = UnityEngine.Random.Range(minX, maxX);
float randomYPos = UnityEngine.Random.Range(minY, maxY);
if (StickUIs.Count == 0)
{
SpawnPos = new Vector3(randomXPos,randomYPos,1);
}
else
{
SpawnPos = new Vector3(randomXPos, randomYPos, 1);
foreach (var stick in StickUIs)
{
while (randomXPos <= stick.transform.position.x - 10f || randomXPos >= stick.transform.position.x + 10f)
{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
if (randomXPos >= stick.transform.position.x - 10f || randomXPos <= stick.transform.position.x + 10f) break;
}
}
}
StickUIs.Add(Instantiate(StickUI, SpawnPos, Quaternion.identity, StickSpawn.parent));
what do you think...
what are you trying to do?
Just to be clear what im trying to do is to not spawn sticks too close to each other
that code doesn't make much sense
use the Graphic raycaster to check if your chosen position has anything there
I just googled for the fun of it, if ~= is an operator in some languages
First result says it means != in LUA 😆
wait look
well shit 😄
i meant almost the same as
Yeah I figured
On the left its all right, on the right that's what I want to avoid.
My recommendation
would Graphic raycaster check that distance?
idk what you mean by that
feels like sumthn sun tzu would say
no problem, come back when you need answers to your questions!
ty
and remember to use the !docs for any function you do not know
definitely. I think I know a lot of unprofessional terminology since I coded for a bit on roblox
seems to have different names here
Like I want to check if the current spawn area is available
And im tyring to do that with while loop
I'm aware what you want
I recommend using the raycaster
it would since this is a real programming language that people use in a profesional enviroment
basically what Im trying to do is that lets say One stickUI spawned at X position 5, if There is another one spawning it should either spawn at X greater than 7 or lower than 3
but you will probably get used to it fast
Well, roblox has an incredibly professional environment all over too. I just wasn't involved in it
you can do this:
do {
// pick a random spot
// use the raycaster to check if there's anytthing in that random spot
}
while ( /* something was in the spot you picked */)
// spawn at the spot
Just don't get caught in an inifnite loop
how would I check if something was in spot with raycaster, and I'll try to do rest.
Didn't really understand anything in that doc
xd
Am I right in thinking that Scriptable Objects can reference things in the project, but not in the scene? (as in public fields?)
if(!StickUI.GetComponent<GraphicRaycaster>().blockingObjects.IsUnityNull())
Does anyone know if after jumping, I can then start listening for isGrounded temporarily? I can't do it prior for a few reasons
Not sure how to approach that
i don't think im going right way...
non-scene objects cannot reference scene objects
Yeah, but can they reference other non-scene objects (for example Materials?)
its best to make your own isgrounded by using a spherecast or raycast or checksphere
yes
yes, assets can reference other assets.
then you can manipulate it in any way
Right, thanks. I thought so, just wanted to make sure 🙂
but how can i raise the gravity ?
I'm aware, but I'm trying to learn other methods first
you could have just.. tried it 😉
I'm planning my code, so wanted to check before I write it all and haveta rethink it. lol.
like what?
like how to use coroutines or task.delays in unity
threading stuff
In the project settings under Physics
you cannot modify the character controller grounded afaik
on your Rigidbody2D component if you are using it
I'm not going to lol
this is why i mentioned making your own
that's not what I'm asking
nvm you have a 3d one
Does anyone know if after jumping, I can then start listening for isGrounded temporarily?
then what are you asking?
I want to either start listening for isGrounded post jump, not prior or delay and turn IsJumping off after 0.5 seconds
one of the two
If you're a beginner I recommend sticking to coroutines instead of async for now
If you think about threading either use the job system, or use UniRX / R3 ( - personal opinion)
Oh if you need multithreading then yeah you need something else than coroutines
As someone who recently had to learn it for my new job, I can only recommend R3 for async / multithreading
not atm, I may get into procedural gen a bit later but I'm too new atm to more complex code
oh that sounds like a perfect task for the jobsystem
I was doing procedural gen for a day and messing with perlin noise color maps and all that
never even touched code remotely that complex on roblox lol
Cool, I'll keep that in mind for sure
Rn, just figuring out simple steps forward with characters
then use a coroutine
and wait for 0.5 seconds and turn jumping off
just make sure the user cant jump 15 times by spamming space before isgrounded turns off 😄
i would check if grounded in jump if statement and i would also suggest moving all of that logic to a private void Jump() so you can call it whenever
do{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
} while (!StickUI.GetComponent<GraphicRaycaster>().blockingObjects.IsUnityNull());```
yeah, exactly. Just doing a bit of a challenge by having a delayed jump
good practice exercise
do
{
randomXPos = UnityEngine.Random.Range(minX, maxX);
SpawnPos.x = randomXPos;
issomething = !StickUI.GetComponent<GraphicRaycaster>().blockingObjects.IsUnityNull();
} while (issomething);```
Shit I think While broke my game
yeah
considering that condition cannot change inside the loop then your loop will never end
either just make that an if statement and stick it in Update (if it isn't already), or use a coroutine and yield return null inside the loop
u know what im trying to do?
these scripts are meant to work together to let me pick up and drop items, but whenever i try picking up any item that isnt the latest one created with the script attached it doesnt let me drop it
its rly weird cos the debug.log that ive dropped it shows up in the console, but nothing else happens and it stays parented and kinematic
no
!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.
whoops
you need to actually Raycast with the graphic raycaster
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.GraphicRaycaster.html#UnityEngine_UI_GraphicRaycaster_Raycast_UnityEngine_EventSystems_PointerEventData_System_Collections_Generic_List_UnityEngine_EventSystems_RaycastResult__
I chekced that doc but didn't understand anything
you need to call the Raycast method
Like how?
these scripts are meant to work together to let me pick up and drop items, but whenever i try picking up any item that isnt the latest one created with the script attached it doesnt let me drop it
its rly weird cos the debug.log that ive dropped it shows up in the console, but nothing else happens and it stays parented and kinematic
https://hastebin.com/share/uxuzutemer.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
there are beginner courses pinned in this channel, you should perhaps start there if you cannot recognize that you are missing the two parameters required to call that method.
No I realize that haha
I just don't know what does those parameters take like what is PointerEventData or the list that it needs
Im good with c# i just have a hard time understanding Unity library
no worries.. at this point in time (starting learning and stuff) docs are a way of introducing you to functions and methods that unity uses.. ofc ur not going to understand all of them..
but the take-a-way is knowing what ur looking for.. keywords and stuff.. can help massively when doing ur own research or looking for other reference material
I do that a lot but thats why I joined this server to like actually understand unity by getting help from people yk
ofc ofc
one thing now is that how would Raycast help me with that?
i enjoy being part of the channel b/c of basically this.
i know how to search and learn my own stuff.. but i can't possibly know all of whats available
yes ofc
users here help introduce me to new functions and ideas on the daily (usually)
yeah it's been two days since I joined and already got a lot out of this server
the graphic raycaster is like ur normal raycast (shooting a lazer into the screen and seeing what it hits) .. but in this case its specifically for UI/ and Canvas
in ur case.. u could raycast onto the canvas and know whether theres already an object where u plan on spawning one..
if ther is.. u can ignore that position and find a new one
rinse and repeat
Does anyone know why my TextMeshPro input field doesn't let me type in it? It's selected, but whenever I actually type, nothing happens
yes but how would check if something was in this radius like for example there are 5 sticks aligned and there is 6th trying to spawn but it shouldn't touch any of other stickUIs radius, also I don't understand raycasting methods much thats why
this isn't code related, but do you have an event system in the scene? i don't see one in the hierarchy
event system?
yeah i do, i think that might be the issue? but without the event system, the input box doesn't get selected when i enter into it
is it possible that setting it selected every frame is stopping the input
possibly
ill fix that
it's only selecting it whenever it's not focused so that should only happen whenever the terminal is first opened
//Code to be place in a MonoBehaviour with a GraphicRaycaster component
GraphicRaycaster gr = StickUI.GetComponent<GraphicRaycaster>();
//Create the PointerEventData with null for the EventSystem
PointerEventData ped = new PointerEventData(null);
//Set required parameters, in this case, mouse position
ped.position = SpawnPos;
//Create list to receive all results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast it
gr.Raycast(ped, results);```
and how do I even know if im going right way xdd
its probably the event system, but im not sure what i could do otherwise, since without the event system, it doesnt get selected at all
is this AI generated code? because it is against server rules to seek help with AI generated code
No
Its this code
from the website other guy gave me
doesnt look like it. usually ai code puts a space after each // before writing the actual comment
plus the comments would be a lot more detailed
I just changed it up to my likes
don't know if im going the right way tho
no they wouldn't. ai code generally has those brain dead obvious comments that say exactly what the line does with no other context.
well anyways it's not AI xd
have you considered testing it?
yes
float minX = StickSpawn.position.x - 9f;
float maxX = StickSpawn.position.x + 9f;
float minY = StickSpawn.position.y - 1f;
float maxY = StickSpawn.position.y + 1f;
float randomXPos = UnityEngine.Random.Range(minX, maxX);
float randomYPos = UnityEngine.Random.Range(minY, maxY);
if (StickUIs.Count == 0)
{
SpawnPos = new Vector3(randomXPos, randomYPos, 1);
}
else
{
//Code to be place in a MonoBehaviour with a GraphicRaycaster component
GraphicRaycaster gr = StickUI.GetComponent<GraphicRaycaster>();
//Create the PointerEventData with null for the EventSystem
PointerEventData ped = new PointerEventData(null);
//Set required parameters, in this case, mouse position
ped.position = SpawnPos;
//Create list to receive all results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast it
gr.Raycast(ped, results);
if (!gr.blockingObjects.IsUnityNull()) { Debug.Log("worked??"); }
if (!gr.blockingMask.IsUnityNull()) { Debug.Log("worked??"); }
}
StickUIs.Add(Instantiate(StickUI, SpawnPos, Quaternion.identity, StickSpawn.parent));```
i have a developer console in my game.. and i had to do something similar.. b/c when you pressed the HotKey to open the terminal the mouse was still locked in the center of the screen so i would have to also press Esc to unlcok the cursor and then click the input.. (so i wrote code that would focus it as soon as the terminal was pulled down..)
This is weird effect im getting but i think its close to what I need Just don't know how to modify it
@inner folio let me see if i cant find my code.. there may be something in there thats helpful
what i'm trying to do is have computers around the map that open a terminal to teach players linux cli cmds, but the EventSystem stops them from people able to type in the input
i originally had a seperate scene for the terminal, but that didn't work since the position of objects in the main GameScene would get reset when i switched back to it
ya, i remember i have my Event System cached into my GameManager script..
b/c i have to manually manipulate it to get my command terminal to work correctly
interesting
i'll look for it
if i dont include the EventSystem, the input box doesn't get selected though which is weird lol
ya, if its a UI element. you need a EventSystem to even interact w/ it
well yes, that's part of the event system's job. you need it because it is what makes the UI work
this is also my first time using unity so im a little bit confused
i didnt have an EventSystem on my original scene for the terminal though i dont think (nvm it was in the root hierarchy)
even weirder
(that one stick is also ui)
omg
you can see i still have a little issue with mine.. *if i dont use a command that changes the scene or something.. then when i close it i have to force my cursor back into locked mode.. by toggling my main menu
i moved the EventSystem into the root hierarchy and it worked lmao
sooo not perfect.. but it works for the first part (focusing on the input)
ohhh soo its fixed now? 👍
cool Tux
his animation is supposed to be a running animation... still havent figured animations out 😭
ya, soo that makes sense.. the event system wasn't working correctly.. b/c it was activated along side of the terminal.
ah okay
best to have it always active before hand.
that makes sense, i didnt think the original terminal scene even had one, but it did by default; i guess whoever started this scene in my group removed the EventSystem or something
like i was saying.. i keep my event system cached.. in the game manager
always nice to have a reference to it at all times (imo)
i see
usually its not very important.. but since i swap entire UI and Canvases I have a Master event system that i carry from one scene to another
it works though :D
hey, if it aint broke dont fix it
what is this tho?
is that running actual windows shell or something?
nah it's just a virtual file system
i should also probably not use C: ... > since its not windows cmds anyways lmao
ya, the C:\WINDOWS\System32 part threw me off
did u code this urself? or is this an asset?
https://assetstore.unity.com/packages/tools/gui/command-terminal-123344 i use this one.. pretty solid over all
coded myself but watched a video for the actual UI stuff
i saw this earlier after i had already made the terminal 😭
i use this one b/c its GUI code...
its not an actual gameobject UI panel
all drawn at runtime.. i like that for whatever reason
yeah
mines probably not optimized at all but i dont really care since im just trying to get this working lmao
the one i linked is very solid.. and easy to use.. if u ever decide to change urs
my favorite part is its tied into the Console.. soo it will log debugs and stuff inside the terminal as well as the console
that looks pretty nice
https://gyazo.com/6ee5f42e998414535c9744103f1e5743 this lava that should teleport you to spawn won't work for some reason.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleporter : MonoBehaviour
{
public Transform teleportTarget;
public GameObject thePlayer;
private void OnTriggerEnter(Collider other)
{
thePlayer.transform.position = teleportTarget.transform.position;
}
}
IsTrigger is on
do they not have debugging in LUA?
using an if statement in the update should work to debug that right
They do
then add some to your code and show the logs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleporter : MonoBehaviour
{
public Transform teleportTarget;
public GameObject thePlayer;
private void OnTriggerEnter(Collider other)
{
Debug.Log("Here to know if your collision takes place");
if(other.CompareTag("Player")
{
// usually theres a 2nd conditional to check for specific objects
// you don't want *any* collider to trigger the logic (usually)
Debug.Log("Also here to know if the collision is the Right collision");
// finally if it is
thePlayer.transform.position = teleportTarget.transform.position;
}
}
}```
What's CompareTag?
you could even use other.transform.position = teleportTarget.transform.position
I get other using the parameter of collider
thanks
I'll write a debug log myself and check it out
its to decide if the Tag is the tag ur expecting.. theres many different types of comparisons tho..
you could check for Tags.. u could check if its on a certain layer.. u can even use TryGet to see if it has a sepecific Script/Component
Not sure if it has that tag unless it's on it by default
I don't know how the unity tagging system works yet
u'd assign it
I'll look into it, thanks bro
you've also seemed to have missed the actual solution to your issue
true.. have you debugged to see if the collision is even detected yet @upper thistle
ahh, good good
that's not it
then the collision works 👍