#π»βcode-beginner
1 messages Β· Page 367 of 1
When the size matters. Such as velocity you'd want both size and direction.
Oh I see
But for player movement, in general we would want to normalize right? Because size is irrelevant?
the length of the input vector is important
no my code does not do that it jumps too the cursor and when i max out the jump force and the cursor is on Y 0 it jumps lower then when the cursor is at Y 10 at max jump force
a joystick can be tilted slightly or all the way
Generally you want to "clamp" the magnitude, because user might want to move slightly to that direction
Not in full speed
can i have controller support without using the new input manager?
You keep saying it jumps "too the cursor". That is exactly what you said you wanted. You apply force that pushes you towards the cursor.
Thank yo so much for the explanation
the old input system can handle joystick input by default
alright thanks
you have to use Input.GetAxis with the right axis names
you want "Vertical" and "Horizontal", I think
no i said that I want the player too go in the direction and not too the cursor
What is the "direction"?
Of the cursor
These two things are identical.
the direction of the cursor and towards the cursor
when i click it goes too the exact position of the cursor when it is in reach
but when it goes the in the direction and has max jumpforce it goes beyond the cursor even when the cursor is beside the player
I can show a video of what i mean
Yes. Show me a video.
is c# made by microsoft??
This looks normal. You jump towards the cursor, and the longer you hold the mouse down, the bigger your jump is.
i had for every jump the max jump force so its not normal
Yes
oh, I think I know what's going on here
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
there docs are ass, cant find anything
The Z part of this position is probably -10
Hello, sorry for interupting here but is there anyone who could help me with my scene colors?
What are you finding?
the C# documentation is very thorough
you will have to show us what you're trying
because that's where the camera is
Set the z part to 0 before you calculate direction
That's causing the jumps to be weaker when the mouse is closer
i just want it up incase i need to find something
most of the jump is towards the camera (which can't happen)
surely you were trying to find something if you're complaining about not being able to find anything
You might as well bring around whole dictionary with you
nvm
mousePosition.z = 0;
like this? ```void Jump()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0;
Vector2 direction = (mousePosition - transform.position).normalized;
float appliedForce = Mathf.Lerp(minJumpForce, maxJumpForce, Mathf.Clamp01(holdTime / maxHoldTime));
rb.AddForce(direction * appliedForce, ForceMode2D.Impulse);
}
or you can do mousePosition.z = transform.position.z, in case the player isn't at Z=0
I want this flame thing to only show when i press W, how could i do this?
GetKeyDown SetActive true
GetKeyUp SetActive false
you need a reference to the object first ofc
though if its a particle system you can just call play/stop
using System.Collections.Generic;
using UnityEngine;
public class showFlame : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W))
{
gameObject.SetActive(true);
}
}
}
``` i did this, but it doesnt work, for some reason
how can I create a looking around feature for my character
first person?
Iv already programmed a wasd movement system
Yes
do you want a clamp on it
did you attach the script to a gameobject in the scene?
yeah its attached
it just doesnt show at all, assuming because of the Start() function?
Does anyone know an easy way to check if all items in a list are active and return something as true if they are?
whats a clamp?
nope, as soon as you press W the gameobject is active
limits their movement on the X a Y axis
so in theory, its meant to work
Yeah sure, i can always configure it later.
yep, GetKeyDown would be better though
whats the difference?
this will only activate it once though
down is a one off, GekKey is repeating. Remember what I said about the docs?
actually this script wont work at all
gameObject is set to Active false, Update doesn't run
yep mb
true
first you need a proper reference to the Flame object.. this is disabling the current object script is on
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class showFlame : MonoBehaviour
{
public GameObject flame;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W))
{
flame.SetActive(true);
}
else
{
flame.SetActive(false);
}
}
}
i've changed it to that
also, for some reason my character just floats up into the air, it was working perfectly fine earlier for some reason
might make it a bt better π€·ββοΈ
provide code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovmentScript : MonoBehaviour
{
public float movementSpeed = 15f;
void Update()
{
if (Input.GetKey("w"))
{
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
if (Input.GetKey("s"))
{
transform.Translate(Vector3.back * movementSpeed * Time.deltaTime);
}
if (Input.GetKey("a"))
{
transform.Translate(Vector3.left * movementSpeed * Time.deltaTime);
}
if (Input.GetKey("d"))
{
transform.Translate(Vector3.right * movementSpeed * Time.deltaTime);
}
}
}
yes i have, still doesnt work
show me which object you put it on
show me the inspector
so you're putting script on an object that disable itself and u want update to run after ?
So then any time you ever are not holding W, this object disables forever
Because it would be disabled, and therefore unable to run update to re-enable itself
ShowFlame goes on the root object, not the one being disabled
should i make it into a prefab, and then add the script to a gamobject?
what?
here i spelled it out for you
#π»βcode-beginner message
no idea how you got that thought from what digi said
You should put the script somewhere else
Anyone use Vim/Neovim with Unity as their editor?
Well I'm using IdeaVim with Rider
i put it onto a empty gameObject and then added the flame onto the Flame object, works now, thanks @rich adder @polar acorn
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovmentScript : MonoBehaviour
{
public float movementSpeed = 15f;
void Update()
{
if (Input.GetKey("w"))
{
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
if (Input.GetKey("s"))
{
transform.Translate(Vector3.back * movementSpeed * Time.deltaTime);
}
if (Input.GetKey("a"))
{
transform.Translate(Vector3.left * movementSpeed * Time.deltaTime);
}
if (Input.GetKey("d"))
{
transform.Translate(Vector3.right * movementSpeed * Time.deltaTime);
}
}
}
for some reason this makes my character object float into the air, any suggestions on why?
I mean sure that works, but you could've easily just added it to the Ship object lol
Do you have a RigidBody attached?
Yep
a Rigidbody wont change anything
the rigidbody is floating if its not constraint locked, collided with something and has no gravity
weeeee
and its more of a question... he said he has a rigidbody.. w/ is helpful b/c hes using translation for movement..
not rigidbody forces
Care to show the inspector?
hey, I have a question, I'm trying to change multiple gameobjects all having their own textfields from a single gamecontroler gameobject having a single script. how do I go about doing this?
how do I reference the gameobject in the inspector, everything I have tried so far is giving me errors
well if he's wanting to change text he might be better to make a list of TMP_Text objects intead
to save a bit of trouble of grabbing the component from every object
you should always try to use the most specific type possible
public TMP_Text[] textObjs;
foreach (TMP_Text textObj in textObjs)
{
textObj.text = "Hello";
}```
Im getting this error?
your IDE should be suggesting a fix
textObjs.ToList().ForEach(t => t.SetText("Hello")) π
Hello. I get this error when calling and already instantiated gameobject with obj.getComponent<LineScript>() ;
NullReferenceException: Object reference not set to an instance of an object
LinkManager.UpdateLineAndNodePositions (UnityEngine.GameObject obj1, UnityEngine.GameObject obj2) (at Assets/Scripts/LinkManager.cs:49)
GameManager+<SwapPositions>d__6.MoveNext () (at Assets/Scripts/GameManager.cs:55)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <e8a406da998549af9a2680936c7da25a>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
GameManager:Update() (at Assets/Scripts/GameManager.cs:36)
its a prefab with a script attached to it. See the image below.
I am missing someting ? Help appreciated π
What does locking the inspector window do?
not even the right game object. Read the error message
You can have multiple Inspector windows/tabs open. Locking one will let you select different objects in different windows.
not sure what you mean, it comes from that line
I think not
LinkManager.UpdateLineAndNodePositions (UnityEngine.GameObject obj1, UnityEngine.GameObject obj2) (at Assets/Scripts/LinkManager.cs:49)
Oh I see, so if I lock one I can keep that particular inspector window open
While navigating to other inspector windows
hmmm, but the objects are not null at line 46-47
unless....
jeeez
obviously link1 does not have that component
You're generating surprisingly many string with that code
How so? π
GameObject.name creates new string every time you access
Btw i found the error, thank you for being my rubber duck π π¦
One of the cursed properties Unity has
Beacuse it's actually saved in C++ side and needs to allocate when you use in C# side
i give all my objects GUID, time to read the docs then...
every dumb thing has a reason that outweighs the dumbness
Should i use tags then or can i somehow get a reference that the compiler gives the object?
GameObject.tag also does the same
But you can use GameObject.CompareTag to not allocate
Tags suck tho
what is the actual purpose of that comparison?
or compare instanceID
one reason why people use that instead of the property
Only reason really
i need to find the object i select from a list.
if it is in the list already, why do you need to find it in the list
Are they actually different object with same name? π
i could also just use var link_1 = linkObjectList.Find(obj => obj == obj1); but i like to give my objects IDs
π
If you can do that..
this is pointless
var link_1 = obj1
good with extra lines of code. Then i can sell it for more on steam
instead of shitposting, you should provide an actual response so that your misunderstanding of what is happening can be corrected
ummmm... what?
thats not so friendly...
I'm sure people care about performance more than extra code
Hmm I cannot detect what would be causing your player to float
i genuinely cannot tell if this person is making a poor attempt at trolling or not
I am trying to transpose these setters and getters however I am running into method must have a return type error. Yet in the original script it works just fine without one. Thoughts on where I went wrong?
Where is the best place to learn to read and write C#? It's hard to explain, but i'm not looking to understand what "GetComponent" does, i want to know why "<>" follow it. I understand what all the functions and methods do, i simply don't know when to write parathesis or less than symbols?
Are you making constructor
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/ best place is str8 from the source
and !learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
I believe so, yes
is ur IDE configured?
Most of these tutorials go into what the methods and stuff do. I know what variables and stuff are, i just dont understand the punctuation within the language itself.
even if u dont know when to use <> or () etc.. a configured IDE should autocomplete and guide u to correct syntax
Constructor should have same name as the class
syntax is the terminology ur looking for
Oh thank you so much
Thank you! Yes, the syntax. Should i simply rely on the autocomplete? That feels like it's going to catch up with me at some point
it'll help know when to use what.. but you should still supplement that with learning thru some of the sources i posted
I'd like to understand WHY they are there so i can understand when to use them
and in the pinned sections
<> is related to Generics
its basically allows u to define classes, methods, and wha-not that can operate on any data type
<DataType>
that way getcomponent can grab a Rigidbody.. or it can grab a Transform.. or w/e
public T GetComponent<T>()
{
// Method implementation
}
``` for example
this would be the function ur referencing.. where it can handle any Component type you pass into it
GetComponent<SpriteRenderer>().color
this line of code is absolutely baffling me. It uses all 3 syntax methods and i have no idea why they are used seperately of each other. What are the parenthesis used for in this scenario?
GameObject.Find("Player")
This line seems like it would be comparable to GetComponent, but instead of "<>", a "." is used?
Then you do need to learn C#
ya, its a bit of an explaination.. i could summarize it for you but that wouldn't help you understand it much better
the () are there.. b/c the method takes no parameteres..
but its part of the syntax and has to be included
it's pretty simple really
GetComponent is a method like Find is a method. methods are called with none or more parameters which are encased in ().
<> is passing a type for a generic method. for the explanation of that read the docs
^ thas a pretty short and sweet explaination
when u use GameObject.Find() its a method that returns a gameobject.. u dont need to tell it a type..
but the GetComponent can be called on multiple types..
it needs to know what to return..
so thats why it has the extra <Type>
How too add a "trail" too where the player is jumping too?
Ohhhhhhhhh! Okay! So <> is used to specify a certain part of something. This isn't always necessary like in the case of "GameObject.Find()" because GameObject is specific enough that it doesn't need further clarification?
ya Find() is a function within the GameObject class..
it knows to return a GameObject
close enough
but GetComponent could be anything
soo u need to pass in a type for it to change its return type
dont want GetComponent<Rigidbody> returning a Box Collider for no reason
when i was learning the . was the best thing i learned about..
<T> refers to the components TYPE
Type is the "name" of the class.
public class MyScript : MonoBehaviour
GetComponent<MyScript>()
It has to inherit from the component class to work (which MonoBehaviour does, and all the things you add to a gameobject do)
ohh i want to access a property of a component.. its component.thingyIwant
a lot of stuff in Unity i still chaulk up to being "magic"
all i needs to know is how to execute that magic
I suppose im still a little confused why "<>" are used instead of "." since in my experience "." is simply used to specify further... But now at least i know when at least one is needed.
Why wouldn't GetComponent.Rigidbody work?
It's called a constructor. Every class has an optional constructor and destructor which is a special method that has no return type and gets called when the class gets instantiated... and deleted, which is done automatically. The original class is fine because that is the constructor of the class, however, the other "constructor" is not fine because the class is not named "Move", which is where the compiler thinks that it should be a "normal" method, and thus must have a return type.
This is the beauty of statically typed languages :)
b/c GetComponent doesn't have a property called Rigidbody
Dot Notation accesses members from the object to the left of the dot. GetComponent is a method, not an object. It contains no members. <> allows generics to be used, meaning it can be any type within set limits (which is that it must inherit from component)
If you wrote GetComponent.Rigidbody, it would imply that GetComponent has a member named Rigidbody, which is not the case. Instead, GetComponent<T>() uses generics to specify the type you want to retrieve. . .
TIL its called Dot Notation π
honestly a good question for a beginner.. its more thought out than lots of hte questions i come across lol
very creative :D
Agreed. This is a good thing to be asking
Inb4 steve says it ruins everyone
i swear visual studio is magic
i use VSCode now..
w/ AI extensions
its terrIble now.. i can type a class name and a few variables.. and boom
it wants to fill in my entire script
damn, but so very, very true
true. but you first pay the dues, then you get the benefit
sometimes u cant force it.. just expose urself to it.. and it'll click eventually
Would you guys reccomend AI integration and stuff for a beginner?
absoultely not
Ah fiddlesticks
as a beginner u can't point out errors... or even find when it goes off track
before u know it u have spaghetti that no one wants to touch
Well im learning to code for funsies, idk if anyone will ever see my code but me
We may or may not be thinking of some specific examples for that
once u start learning how to code im not anti-ai
its super helpful for some things... like refactoring code..
But if its making errors then i could see how that may be an issue
or writting long boring boilerplate
it does..
very often
even has a disclaimer w/ most of em lmao
just use ur own discretion
Yeah thank you for listening to me btw! I usually use ChatGPT but this question was too confusing and difficult to word for an AI to understand what i was asking
idk how i feel about defiant and rebellious AI
Thats how you get terminator'd
That's a good point. The benefit of asking here is people will tell you that what you want to do is dumb and suggest a better way
!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.
You can save the links
Welp im off to make more horrendous sloppy code that is slightly less horrible and sloppy than last time! See ya!
the usual simple ones. Pong, Breakout, Angry Birds, Floppy Bird
lol
saw that
What did I do wrong? How come it's missing a referencee?
I think so, yeah
where did you define it ?
I thought it was defined in my base
according to your IDE it doesn't exist, unless you are missing the namespace if you used those or another assembly?
I don't know how to use another assembly so that might not be it
Private cannot he used by a child
just show where you define a type ElementType
You then never made the ElementType π€·ββοΈ
What do I need to do in order to change what game objects are selectable here? Right now it is able to select the undesired moves
[System.Serializable]
public class LearnableHiraganaMove
{
[SerializeField] HiraganaMoveBase hiraganaMoveBase;
public HiraganaMoveBase Base
{
get { return hiraganaMoveBase; }
}
}
nothing here i think
but in the HiraganaMoveBase class
your list is a List<LearnableMove> which is, notably, not a list of LearnableHiraganaMove
those classes aren't even related
Thank you so much!
Having a strange problem, Dictionary.ContainsKey is not working I think.
I have a Dictionary of crafting recipes defined like so:
static readonly Dictionary<ItemType[], ItemType[]> craftingRecipes = new Dictionary<ItemType[], ItemType[]>
{
{new ItemType[3]{ItemType.Rope, ItemType.Stone, ItemType.Stick}, new ItemType[1]{ItemType.Axe}}
};```
And later code to check if a provided recipe exists
```cs
void CraftRecipe(CraftingQuery craftingQuery)
{
Debug.Log("breakpoint");
if (craftingRecipes.ContainsKey(craftingQuery.recipe))
{```
And I'm *sure* that the recipe I'm providing exists in the dictionary, as shown in the pictures, but the if statement is returning false.
you're using an array as the key. it's not checking the contents of the array, it is checking the reference. so when you check if it contains the key and you pass a different array object that just happens to have the same elements, it is going to return false because it is not the same array object
create a struct that holds a list of ItemType, and override GetHashCode on that struct to combine the hashes of the list elements or something π€·ββοΈ
Hmm okay, I'll see what I can do. Thanks π«‘
can someone help me reference this child image named "Crosshair" under the canvas "defaultCanvas"?
I tried to put in a variable but I think something is wrong: public GameObject crosshair = defaultCanvas.transform.Find("Crosshair").gameObject;
error: error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyFirstPersonController.defaultCanvas'
you need to run that code in Start or elsewhere
you cant do it where you actually make the variable
also if you can, just drag it in the inspector
assigning it via the inspector is the best option
ok so I just assign it as a gameobject in the inspector then I can set it to active or whatever
yes
alright thxs
Can you serialize scriptable objects to store them as json?
Shoot where did I go wrong here?
your adding a different Type to the list
i'm guessing that HiraganaMoveBase does not inherit from MoveBase despite the name implying that it does
just like how LearnableHiraganaMove did not inherit from LearnableMove
Hmm let me do some digging
[System.Serializable]
public class LearnableHiraganaMove
{
[SerializeField] HiraganaMoveBase hiraganaMoveBase;
[SerializeField] int level;
public HiraganaMoveBase Base
{
get { return hiraganaMoveBase; }
}
public int Level
{
get { return level; }
}
}
Did I declare something wrong in this HiraganaBase script?
this is not the HiraganaMoveBase class, nor is it the HiraganaMove class
Here's my HiraganaMove class
public class HiraganaMove
{
public MoveBase Base { get; set; }
public int PP { get; set; }
public HiraganaMove(MoveBase pBase)
{
Base = pBase;
PP = pBase.PP;
}
}
Sorry I'm new to constructors so I really appreciate this
notice how your constructor expects a MoveBase parameter
Omg thank you so much
you really need to start reading your own code
Hello, I have a function, used in different script of different game objects, but I don't want to copy past this function to every script, is it a good idea to create a static class, i.e static public class Functions, and call the function Functions.MyFunction() in any script? Donβt want to use gameobject.find
Or there is alternative way to do this in unity?
what does the function do? how many scripts use it
you can't use any other fields in that function unless the fields are also static, its get messy
another option is to use a static instance of a regular MB instead , to access its methods easily those are best suited for like game managers and alike though
Hard to say without knowing the context of the function and what information it needs to do its job
for example this function, i ll call the function Functions.FindAvailableGameObjectFromList() in any other script if I needed, and is there an alternative way to do this, without using static and gameObject.find().getcomponent.FindAvailableGameObjectFromList()?
Unity already have functions like this built in
FindObjectsOfType etc.
currently static is giving me issue, when two scripts calling the function at about the same time, it messes up the value
huh mess up the value how ?
@rich adder hey can u help me with smtng
huh?
ayight my bad
i'm having a trouble to make the bones following the gun when i aim
well I know nothing of your setup , I can't possibly know what it is
can i stream f y
π 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.
is gonna take a while
start with the code and some screenshots
in the ChangeAnimationState() function, I swap animation state using .Play(), between enemyActive and enemyDied, from the console, you can see a hash that is not belong to enemyActive nor enemyDied
I found a solution but I donβt know where that hash number from
@flint python why do you even need that static function in the first place, I don't even know why
!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.
So like when you want to use the same function in different script, but you donβt want to duplicate the code
that explained nothing of what that function is *supposed * to do
this smells like an XY issue
so what controls the bones exactly ?
o haven't used the 2D ik package yet
is your right hand target not paranted to the gun ?
i put the gun inside the Rbicep
so which one is not following
have to show the video or I can't tell whats even happening instead
wait i'll make avideo
the left arm ain't reaching the gun position
and the flickering thing
i created a new animator layer
with shooting animation
holding the gun
and in the script i switch the weight to 1 when i aim
which one controls the chest IK. I have to brushen up on 2D IK since I've only done the 3D one
bone spine 1
thats probably the one you want aiming at the Aim target instead of rotating the hands that already hold pistol
so what i'm gonna do
the bones r aiming towards the cursor actually
this is the aim animation
yeah you probably dont want to aim alll thse bones though
there's any way to rotate the arms
you need a root bone that rotates multiple bones
Ie both arms inside 1 common parent and rotate that
yeah but you probably just want to do the spine2 bone
didn't understand
If art school says nein, then the world is mein
spine / chest bones moves both arms
Ill try to see how 2D IK work and report back
thank y
So my player has a script that allows him to pick up specific objects by holding E, but I think it's making trouble with other scripts, and preventing them from working. I have another script that is as simple as "If this object overlaps with another of a specific tag, an inactive object is enabled", and it doesn't work when the two are clearly overlapped. Can anyone spot anything here that might be the prob?
The code for the box mechanic is this one
https://gdl.space/xuxowurige.cs
And here's the simple one that's just for the empty box detection
using UnityEngine;
public class PortaPainelSolar : MonoBehaviour
{
public GameObject objectToActivate;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("LuzSolar"))
{
if (objectToActivate != null)
{
objectToActivate.SetActive(true);
}
}
}
}
I tried dding debug logs to find out the issue, and for some reason he is not detecting when it collides with the other object with the specific tag
Could it perhaps be an issue with how he picks up the box?
Hiya, basically I have implemented a script that made sure, whenever my player touched the wall while jumping, my player wouldn't get stuck to the wall instead the falling animation would commence and the player would cease any movement until i moved in the opposite direction but after i implemented it and started the program again my character just gets stuck in one spot.
Here is my script
is there a way i can access an object from code just code no assigning through a variable?
GameObject.Find... π
What did GPT say
i asked it the same question
and it gave me find gameobject options
sorta like you did
in this case i did by type
which was an audio source
Yeah those are not the best performance but if you don't want inspector there are not much options
well i was trying to assign it to a prefab
but while it was a prefab
it said the type was wrong'
but when i inserted the prefab and manually assigned it it worked
now i can hear a clunk sound with all of my bread π
The LoadData method gets called when scene starts, and then it calls the DelayedPositionChange method. This waits a bit and then sets the position of the player and rotation of the camera. For some reason, the rotation of the camera will not be set. I printed out the rotation in the data object and it was correct, but it seems the rotation of the camera holder cannot be set at start! Why is this?
do you have something else setting rotation ?
What is setting CameraHolder and what is calling SaveData?
I've just fixed it myself, sorry. I had a variable as a Vector2 that was 2 floats that stored the rotations in floats, just had to change it to a vector 2 in my save class.
It was being overridden.
I have a Vector2 called, camera rotation, it stores the X and Y rotation of the camera.
I don't need the Z
When you move your mouse it does cameraRotatio.X + mouseX value
So, it started off at 0,0 and I had to just change it
oh ok
Has anyone tinkered with GitHub Copilot with Unity scripting? Any thoughts on it?
its alright from what I saw, nothing impressive other than simple autocomplete
I see I see
Not worth it, I've tried.
not really
You could probably put it in another update and put the Order of script sooner on that one
https://docs.unity3d.com/Manual/class-MonoManager.html
idk what you're trying to accomplish with a "pre/early update"
This frame's late update is next frame's early update π
was kinda just a hypothetical qustion π
what are the benefits between using a hashset and a list?
Is there a way to make a dictionary that is accessible by all objects without needing to be created on an object?
I think that it would have something to do with classes, but I'm not really sure. Any help would be appreciated.
HashSet does not allow duplications and does not maintain order
nope
Not by default at least
Can't Unity-serialize β’οΈ
odin inspector probably could
always wondered, why can't decimals be serialized in the inspector
but i've had severe perforamnce issues with that installed
theyu cant??
i dont use them but
What are you trying to do with that dictionary? Are you looking for some kind of singleton object that shared across entire game?
It can. Not just that though
yeah had to just use floats :\
I want to store all of my terrain info inside of it.
You can use static variable for that, but mind that it is not really expandable way
Alright, I'll give that a try, thank you.
put it on a scriptable object π
Noooooo
That'll be my fallback yeah, but I'd rather not have a bunch of objects that just exist as references for other objects.
if it was a list I'd say do so, but cant even serialize dictionary anyway so keep it static
For context is this something that changes on runtime?
Yes, it will change when more terrain is generated.
I see then I think static should be fine, you might need to handle cleanup tho
if you're like me and also use domain reload off be careful
all the sudden your dictionary has thousands of entries xD
Alright, sounds good, I'm just researching static variables right now, since I very seldom use them, but thanks for the help.
How do I stop a memory leak (if that is what it is), I accidently started an infinite loop and now even when the game isn't running I'm getting errors!
Restart the editor
Does anyone have a site/app that will help me understand and know how to use c#
I would say either the C# docs page or watching lessons on YouTube
Ok π
how do I disable those gray text suggestions?
Tried googling but idk what they're called in the first place
I recommend avoiding youtube
even if you're not watching tutorials on your problem and just watching lessons on coding in general?
like learning how to do lists or dicts?
Yes
can i ask why u think so? not saying ur wrong just curious
Because it doesn't teach you to read docs like text lessons do. The one I linked has you do tests and interact. And youtube vids are just generally not great
Yea I guess thats fair, its important you know how to read through the docs
Plus people generally end up watching brackeys or code moneky or someone else that has a good personality and gets monitized but is not great
How come my Hiragana bar isn't populating?
public class HiraganaBattleHud : MonoBehaviour
{
[SerializeField] Text hiraganaNameText;
[SerializeField] Text hiraganaLevelText;
[SerializeField] HiraganaHPBar hiraganaHpBar;
public void SetData(Hiragana hiragana)
{
hiraganaNameText.text = hiragana.HiraganaBase.Name;
hiraganaLevelText.text = "Lvl" + hiragana.Level;
hiraganaHpBar.SetHP((float)hiragana.HP / hiragana.MaxHp);
}
}
intellicode
Just my luck?
You didn't say what ide, but here
https://stackoverflow.com/questions/70011719/visual-studio-2022-turn-off-grey-suggestions
oh vscode but thanks
thats the intellicode suggestions
ohhh intellicode
disable the extension
cause intellisense would clear other things I use as well
intellisense is more like the star on variables or your most likely to use method/field from class you referenced
On the install thing it says to use something called βConsole App (NET.CORE)β but all I can find is β(NET.framework)β I thought I followed the steps correctly
thanks
never knew it was AI
so thats why it spits out nonsense 60% of the time
yeah it was broken on VSCode for a while
the one on Visual Studio is far superior
but at the end of the day is just fancy "autocomplete"
It's just for practicing. Any console one is fine
it really is
they also have online compiler you can practice on
like the one on their site, microsoft has one too or Dotnet fiddle
I have 2 different canvas' here and Im sure theres a better way to do this. Currently I have "Default" canvas which holds crosshair, 3 sliders, and hotbar. On the "Inventory" canvas it holds a copy of the 3 sliders, copy of hotbar, inventory slots, avatar holder, and armor slots. Just copying these elements into the other canvas makes me put multiple copied lines which do basically the same thing because I have to then update the slider values and text values on both canvas'. Would it be better to put them both on 1 canvas and toggle the gray background along with the other elements? I made 2 canvas' because I only needed the background on the inventory one
This works fine but I feel like I prob shouldnt have just copied the elements over and copied some lines of code to make sure both were updated
might bring up problems when I actually implement inventory because I would then be writing 2x the code
actually yea I figured out a better way I think
you'd write the same amount of code no matter the amount of canvas
do you want two or one is up to you
I just remade it, Ill show u the code I had vs what I have now..
// AFTER CHANGE
public Slider healthSlider;
public Slider chargeSlider;
public Slider usabilitySlider;
public TMP_Text chargeText;
// BEFORE CHANGE
public Slider healthSlider;
public Slider invHealthSlider;
public Slider chargeSlider;
public Slider invChargeSlider;
public Slider usabilitySlider;
public Slider invUsabilitySlider;
public TMP_Text chargeText;
public TMP_Text invChargeText;
I moved the components of the 2 views together onto 1 canvas and just set the inventory to toggle and made sure the background was in the right position
this was just the variables but I had more lines where I was changing the same thing just on 2 different canvas'
Is there one you recommend
Idk if its unity bug or not, but when i try to instantiate something null, it creates infinity ammount of objects from other list in script and soft locks editor
I cant even look in Console what causes this
And i have to stop editor trough task manager
Break with the debugger.
debugger?
nvm i found what was glitching
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LogicScript : MonoBehaviour
{
public int playerScore;
public Text scoreText;
public GameObject GameOver;
[ContextMenu("Increase Score")]
public void addScore(int scoreToAdd)
{
playerScore += scoreToAdd;
scoreText.text = playerScore.ToString();
}
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void gameOver()
{
GameOver.SetActive(true);
}
}
how do i disable a function after another function happened in a different script
Thanks
It really makes no difference at all for what you'll be doing
Where did I go wrong? I'm getting an object not sent to an instance of an object error yet I set the values in the inspector as intended
public class HiraganaBattleHud : MonoBehaviour
{
[SerializeField] Text hiraganaNameText;
[SerializeField] Text hiraganaLevelText;
[SerializeField] HiraganaHPBar hiraganaHPBar;
public void HiraganaSetData(Hiragana hiragana)
{
hiraganaNameText.text = hiragana.HiraganaBase.Name;
hiraganaLevelText.text = "Lvl" + hiragana.Level;
hiraganaHPBar.SetHP((float)hiragana.HP / hiragana.MaxHp);
}
}
Maybe you're setting to wrong object
Or you are referencing wrong object
Double checked but I'm not sure that's it
check if there is some duplicate instances of that script
hello, i've come back for yet another question
im trying to change the outline of TMP through code, anyone knows how to do that?
particularly the color
how do i get my code colored
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
Oh
ah thanks
Tagging it. c#
It should be cs
Block with three ` and then c# added to it
yh
Huh? Both work fine
wait how am i tagging
cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pipeMiddle : MonoBehaviour
{
public LogicScript logic;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3)
{
logic.addScore(1);
}
}
}
yea tagging not going too well
I'm uncertain if things have changed but it should be cs and not c#
https://gist.github.com/matthewzring/9f7bbfd102003963f9be7dbcf7d40e51#syntax-highlighting
how though
Oh I see
Learn something new everyday
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
c# love life
That would be configuring your ide. !code would be how to properly post code on discord.
cs not c#
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i did that bruh
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pipeMiddle : MonoBehaviour
{
public LogicScript logic;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3)
{
logic.addScore(1);
}
}
}
nvm
what
i cant type there
it blocked me from saying there
No need to comment about it or post an ss. Kinda defeats the purpose
what purpose
Spam block - excessive short sentences as a pattern (in this case, a single word)
oh
Stopping spam and overly short messages
no i need help please
sarcasm
You'll need to describe what you're needing help with: error, unwanted behavior, what's happening, what isn't, etc
what i said here
With a bool
What in particular are you trying to disable? What's occurring in the other script?
Just set it false, and if it is false, don't run the function
Hard to say more with that little detail
ok but
hold on
tryna disable point script for a object thingy
trigger
i made a logic function
no
script
and its got the functions in
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LogicScript : MonoBehaviour
{
public int playerScore;
public Text scoreText;
public GameObject GameOver;
[ContextMenu("Increase Score")]
public void addScore(int scoreToAdd)
{
playerScore += scoreToAdd;
scoreText.text = playerScore.ToString();
}
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void gameOver()
{
GameOver.SetActive(true);
}
}
and the player script in the other
hold on
and a trigger script
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor;
using UnityEngine;
public class birdScript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
public float flapStrength;
public LogicScript logic;
public bool birdIsAlive = true;
public double deadzonelow = -8.36;
public double deadzonehigh = 8.36;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && birdIsAlive)
{
myRigidbody.velocity = Vector2.up * flapStrength;
}
if (transform.position.y < deadzonelow)
{
logic.gameOver();
birdIsAlive = false;
}
if (transform.position.y > deadzonehigh)
{
logic.gameOver();
birdIsAlive = false;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
logic.gameOver();
birdIsAlive = false;
}
}
but thats the player one ofc
this exactly why that bot exists btw
(You can like have a thought before hitting enter)
Just clearly state what you want, preferably in one message
Is it when the game ends you want to stop adding to the score?
if (gameOver) return;
In gameOver() set gameOver to true
I tried that but it still remains stationary
Well addscore of course
of course!
mainMenuTitle.color = Color.HSVToRGB(bgCamPartyHue % 1, pulseColor * 10, 1f);
mainMenuTitle.outlineColor = Color.HSVToRGB(bgCamPartyHue % 1, pulseColor * 10, 0.45f);
I know pulseColor is working because the color of the text is changing
but the outline doesn't
i honestly don't know what im doing wrong
nah sorry you're gonna have to be a bit mroe specific there please
in where i put it
oh i get it
wait so it ends that function
Holy MOLY!
t riffic
can anyone help me with making hipfire sway system just like Insurgency Sandstorm?
That is a very broad question. To get help you would need to start things off and ask about specific problems
I did but really didnt understand much I researched about it and asked chatGPT but couldnt find anything close to what I want
soo does anyone know how to help?
I doubt you will find a step by step tutorial to do exactly the specific mechanic you want. Think about the problem and break it down into smaller logical pieces. Then start researching the individual pieces.
I really didnt find any step tutorial like that I find sway and I did it already but I want the weapon to look different directions and not just middle of the screen when I move the mouse
like insurgency sandstorm
Please read what I wrote again π
but I didnt found any
Read what they wrote again, this time slowly.
Read it just one more time please
maybe I am not understanding because its 10 AM and I didnt sleep
Then get some sleep. A rested brain is the first thing you need to program
what does get; private set; do?
makes property accessible globally but can be assigned to only locally
I'm having kind of a weird tricky problem:
I'm trying to set up a character controller + third person camera, the camera is a child of the playerGO and is a cinemachine camera with Look At and Follow set to an empty sitting on my playerGO , that rotates according to player input. My inspiration for this camera setup is something like what Genshin Impact got, where the camera doesn't rotate based on where the player faces, but the rotation axis of the player changes based on camera direction. I got the latter working, but i can't get the player to look at any direction cause then the camera changes rotation too. I can't have the camera as a separate object cause I'm on netcode and it would be an hassle to do so. Any ideas?
How can i make that it isnt slippery?
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0;
Vector2 direction = (mousePosition - transform.position).normalized;
float appliedForce = Mathf.Lerp(minJumpForce, maxJumpForce, Mathf.Clamp01(holdTime / maxHoldTime));
rb.AddForce(direction * appliedForce, ForceMode2D.Impulse);
}```
Maybe add a grounded check and kill the velocity when it's true
ok thanks π
You can also change the friction of the ground
There's a thing called physics material 2D, both colliders and rigidbodies may use it.
You can also use it to chance the bounciness.
You can use Vector2s
doesnt work because now i cant jump (atleast idk how)
Because you have done it wrong enough
When you just, update a boolean isJumping.
then you implemented it incorrectly. You only need check it whilst you are already in the air
So start the Jump method and set isJumping to true. Then, when isGrounded and isJumping, don't call Jump anymore
hey! i have 2 different scenes, but i want to protect my character's stats, also things like the health bar and coin count. How can i achieve that between my scenes ?
use Dont Destroy On Load objects
resetting my character's coin count and resetting health is not an issue, it wont be problem but i always want to see the health bar and the coin ui
what does that mean ? is it works like when the scene changes some object will not be destroyed ?
yes, I suggest you go and read the docs
thanks
Use PlayerPhysics
thank you it works now : )
how too make that it isnt glitchy? (jump at the end)
Does not look' glitchy' to me. Define 'glitchy'
i mean that the player jumps a bit high instantly when hitting edges
I see it now, that is an artifact of the physics system. Again you can cure that by killing velocity oncollision enter
like that?
{
if (other.gameObject.CompareTag("Boden") && inair)
{
inair = false;
rb.velocity = Vector2.zero;
}
}```
may be better to set a flag and do that in FixedUpdate
ok
your other option is to use the physics materials and set bounciness to none if, that is a general behaviour you want
didnt work
didnt work too : (
post your full !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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
code looks fine. Is the collisionenter actually firing?
Yes
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.EventSystems.EventTrigger;
public class Movement : MonoBehaviour
{
public float moveSpeed = 5f;
public float rotationSpeed = 5f;
void Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector3.down * Time.deltaTime * moveSpeed);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector3.up * Time.deltaTime * moveSpeed);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector3.up * Time.deltaTime * moveSpeed);
}
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y, Camera.main.transform.position.z));
Vector2 direction = new Vector2(
mousePosition.x - transform.position.x,
mousePosition.y - transform.position.y
);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
}
}```
i have a movement code and the rotate to where the mouse position is code, but the movement gets affected when i move around my mouse, i want it so if my spaceship is looking to the left and i press W, i still want it to go up instead of it going left, how could i do this?
' i still want it to go up instead of it going up,' ?
also !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.
left* sorry, im tired lol
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Is there a way to not make a child object inherit the parent's rotation?
you probably want to be using transfor.up, right etc rather than Vector3. but tbh your code makes little sense
dont make it a child
Update its rotation manually from a script every frame
Thats a bit unusual though
..yes, but having it a child would make my life so much easier. I have a per player camera in my (networked) game, and having it spawn along with my characters would make my life so much easier
try this
Empty Object / Apply movement here
Child1 //Apply Rotation here
Child2 // No Rotation
in a way i'm kind of doing that already, but it glitches in and out at times
how would i do left and down
negative?
yes
whats the difference between them?
one is world space, the other is local space
How are you doing it
Execution order matters here. Nothing else should rotate the parent after you update the child rotation each frame
My current setup is:
Parent // movement logic
Child #1 // aimPoint of my camera, which is an empty that rotates on input
Child #2 // empty with a camera as a child that is set to Follow/Look at the Child #1 that rotates.
If i turn my parent object, the aimPoint rotates along with it making the camera rotate too.
so move the rotate logic to Child 1 as per my example
my aimPoint 's rotation is updating from player input in update, and aimPoint's parent object (the player object) rotates it's transform based on WASD so aimPoint's rotation ends up switching from the player input rotation to the one overlapped by the parent's rotation
got it, i'll try
ur a lifesaver
tysm
hello guys
i have a small problem
i cant refer to my script (which is in assets) but i can refer to a prefab, is this intentional or am i doing something wrong
Do any one know why clipping is happening the code that i am using to spawn the bullet hole is this
Instantiate(bulletHole, hit.point, Quaternion.LookRotation(hit.normal));
Is it a MonoBehaviour?
Are you trying to reference a scene object from outside a scene?
oh wait i forgot to say
this is a scriptable object
gameplayMusic.loop = false;
gameplayMusic.playOnAwake = false;```
is there a way to simplified this code?
Z fighting. Might want to offset your bullet holes a bit away from the surface.
And the object you try to reference is in the scene?
This is a script asset. Not an instance of the script. You can't reference it.
it is attached to the prefab
Looks simple enough to me.
Ok, so you try to reference the prefab?
Take a screenshot of the prefab.
I'm not very familiar with 3D but I think adding some offset should work
Vector3 offset = hit.normal * 0.01f;
Instantiate(bulletHole, hit.point + offset, Quaternion.LookRotation(hit.normal));
Use the hit.normal so the offset will be always over the face of the wall. Maybe instead of 0.01f should be a higher float, i don't know
i want it to looks more simple like this
AudioSource audioSource = new AudioSource{clip = music, loop = false, playOnAwake = false};
Well, you could create a method that encapsulates these 3 lines.
This doesn't look like a prefab
If it's an object in the scene, you can't reference it from outside the scene.
thanks it worked
Ok, close the prefab edit mode and try to assign that prefab to the serialized field.
I don't know what you were doing, but probably something wrong.
The + symbol?π€
Aah. I see. Don't know why that wouldn't work if you selected the correct object.
i dont understand wdym
You could put these 3 lines in a method and call the method instead.
What part of it is unclear?
you mean a function?
In C# functions and methods are basically the same thing.
Method is the official terminology though
did unity c# syntax changed so big that tutorials made 10 years ago wont work?
no
thank you!
my game runs in the editor but not in the build, can anyone help?
the UI gameObjects doesn't appear
make a development build and then check the player log
Does anyone know why when I give it a build and run in the game it's a different speed and in the scene it's different from what it is
You wrote code that is framerate dependent
You would have to share your code for us to get into more detail than that
Yo.
I have a small problem with code for animation/moving character
This code looks serviceable, but Unity gives an error
NullReferenceException: Object reference not set to an instance of an object
And character can move, but without animation
you need to share the complete error message including the stack trace
Here you go. A lot of errors.
right, now read those and look at the script you posted
yep wrong script entirely @queen adder
nobody actually bothers reading the error messages. It really pisses me off
how do i do that?
you make a development build by selecting that option in the build settings. you read the player log by looking at !logs the docs
I'm so sorry, but I'm beginner, that script was useless, I deleted it. But even so animation It also doesn't work.
Now there's no error. But animations still don't work.
Sorry.
@queen adder acc
i am stuck when i try launch ms vs with a component in unity i am greeted w normal vs instead of ms vs what do i do thanks
Wdym by "normal vs" and "ms vs"? Visual studio is made by Microsoft
Do you mean Visual Studio instead of Visual Studio Code?
I think he means VS Code. He needs to regenerate project files
yes, screenshot External Tools window from Unity
use the actual names of things, not names you came up with
that will help us to know what you're talking about
is this what u want or sm else?
does that even look like it may be the 'External Tools Window' ?
Edit->Preferences->External Tools might be a good place to start
Does it say 'External Tools' ?
omg. Did I not just say that?
That depends, which one would you like to use?
it works thanks for ur time
How do I link my VSCode to my Unity?
!IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
Quick question. If I want to do things as in "systemic design", can I put for example main thing and label it as fire and then refer to it when I use it in projectile for example? Like I have "big" mechanics separate and just refer to them in smaller things?
i don't understand your question
it kind of sounds like you're describing object oriented programming as a whole
like a master class? full of variables or structs that u can reference later?
I won't lie that I understand but I guess (at least from what google search is telling me)
So the easiest thing explanation I can think of would be it.
We have 3 main structures that have X, Y, Z under them like when you label enemy as a enemy in game.
For example we have enemy. I put label on him that he is enemy, player can damage him etc, but I also want to label him Fire.
When I label him Fire I want to everything that is under Water (other enemies, player attacks or environment) to make something happen when it came to contact with objects with label Fire (whatever I put as reaction between Water and Fire).
The question is would such "label system" work?
I'd call these "traits". It's a decent strategy for creating complex behaviors
Are the other ways to creating such things?
i just created a script why does this happend?
you already have another class called Flashlight
ohh ty, for some reason the script was duplicated
!collab
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
Hey! I made my game with levels. When i finish one level, i go to the another scene. it goes like that. I made a game over menu and i rotated it to my main menu scene, but as far as i understand i cant return to the scene that i already visited. is it true ? how can i solve this problem
you can load into any scene as many times as u wish
the really wild part is that you can load more than one scene at a time, too!
(but that can come later)
π―
good afternoon guys, I am starting playing with Unity and i am currently following a great tutorial The Unity Tutorial For Complete Beginners and i have been stuck for the past 5 hours understanding why i am not able to get the same result as he is. 31 minutes in, everything works. but once it is time to get everything to work at 35:45 minutes in, it doesn't work... i have failed to find the reason even after looking back 50 times and i have no code error either in Unity please help
Care to post your code?
we can do very little if you don't show us what you're doing, what's going wrong, and what you've tried
alright, do i put screeshots?
Either post small code snippets of the problem area or use the following tool for large ones
!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.
Also describe (or post screenshots) of what is happening and what is your intended behavior would help
public class LogicScript : MonoBehaviour
{
public int playerScore;
public Text scoreText;
[ContextMenu("Increase Score")]
public void addScore()
{
playerScore = playerScore + 1;
scoreText.text = playerScore.ToString();
}
}
this works
For inline code please use three back quotes (`)
sorry... i am new to this and i find it tricky
So i am assuming you are trying to make a score keeper? What seems to be the problem?
yeah
whats tricky about this
english is not my first language
visually speaking, because the bird has passed to pipe, the number should be 1
its not mine either but I understand simple text instructions that have it written out.
not necessarily, how do you run
addScore
also !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
that is the next part of code linked to it
Debug.Log the trigger
check the pipe prefeb and see if the collider2d is set to trigger
Show the trigger colliders. Do you start INSIDE the first one?
alright, thanks. i will check that
the collider is set to trigger, and no i don't start inside
did u set the logic manager to logic tag like he said?
yeah
Have you Debug.Log the trigger yet? Make sure it's firing?
i will do that now and see what is happening
Okay take your time
Hello, how do I change the value of an attribute in a XmlNode? Google search says to use node.Attributes[code] but Attributes is get only, not set. So I can't edit it...
what is XmlNode used for in unity?
are you deserializing an xml file ?
I use Xml to store and load data, for mods in my game
I'm creating a UI to edit Xml so players can create mods directly in the game, standardizing stuff
I use XmlDocument to load the xml
Well, I didn't know that and I'm used to Xml so I went with it...
oh ok
you are trying to change what exactly I'm not familiar with XML formatting in c#
seems like node.Attributes is the way to go
Well, let's say I have a simple XML file <e><event code="blabla"></event></e>. I just want to change blabla to blibli for example.
Attributes is get only
XmlAttribute attribute = node.Attributes["YourAttributeName"];
if (attribute != null)
{
attribute.Value = "NewValue";
}
else
{
Debug.LogError("Attribute not found.");
}```
I think
Im quickly scanning through unity Forums π
Will the XmlAttribute be an actual reference to the attribute in the xmlnode or a copy ?
you probably forgot the .Value
node is XmlNode node = xmlDoc.SelectSingleNode("//YourNodeName");
I didn't try this way cause I thought Attributes would not return a reference.
I'll give it a shot, thanks.
np. lmk if works. I can test it myself too rq when I'm back on pc
Any luck?
How do you determine the order of precedence for which systems you program? Say I am making a Pokemon style game would I program the camera first then gameplay? Do them simultaneously? Any insights appreciated
well... my lack of coding knowledge is currently beating me good... i am still trying to figure out how to run that
the page I linked has step by step, did you folow them ?
you should at very least be able to verify if logs are printing
Start here @fallow frigate
private void OnTriggerEnter2D(Collider2D collision)
{
logic.addScore();
Debug.Log("Triggered");
}
i dont have a DisplayName avariable inside of my Oculus.Platform.Users.GetLoggedInUser().OnComplete(getname)
private void getname(Message msg)
{
name = msg.GetUser().DisplayName; // i dont have DisplayName but i DO have ID and OculusID
}``` please help
alright, i will do that
Ok it worked! Unity is so confusing when it comes to knowing if values returned are references or not :x Thanks again π
Did anything print to the console?
nope
Do you have collider attached to the game object?
did you resize the collider right?
np!
Honestly unity makes it extra easy because the inspector you can see values like private vars. I just think working with JSON is soo much easier in c# especially since its Object oriented. Idk I just found nodes and stuff annoying to work with
i have a box collider for my trigger if that is what you are asking
yeah
boxcollider2d right?
show the inspector for the object this script is on
what is DisplayName
no shit
but it doesnt exist
and ?
for the third time it just DOESNT EXIST
i physically cannot get the display name
Can you link the documentation? I can't find it anywhere
me?
Yes please
this should be it
i linked the place i got the code from but the docs should be
https://developer.oculus.com/documentation/unity/ps-get-started/
Describes the steps to download and set up the Meta Platform SDK for development with Unity.
What's Logic script do? It appears to be missing
they have the FindObjectByTag
yeah exactly
Box collider 2D
you got 3D colliders, they will never work with 2D functions / rigidbody
not the same as box collider
they are completly different physics system
Thank you, but this documentation doesn't show your method call
yeah idk the exact documentation because i cant find it either, that's why im going off of what i can find and this is the only thing i can find
and make sure rigid body is 2D too
or did you mean something else
No no that''s what I meant @wooden minnow. I guess the documentation is a bit sparse
oh yeah, alright, i will go through my mess and check that. if i have a precise question once i have done that i will say.
here is the definition for Oculus.Platform.Models.User
it indeed includes a DisplayName
mine doesnt
I cannot find a version of the SDK that doesn't have this property.
i dont have the DisplayName variable
Did it work? Swapping out the colliders?
are you using the correct object
what version of the Oculus SDK are you using?
wdym
also, do you mean that you're getting a compile error here?
yup
nvm I see the object comes from a callback
and what is the exact error?
it just doesnt exist
is it IDE or just unity?
if i try to write .GetUser().DisplayName it doesnt autofill and tells me that User doesnt contain the definition for DisplayName
using VS2022
does Unity also complain?
idk?
it cant compile
because of the same error you're seeing in the IDE?
or because of some unrelated error?
yeah
screenshot the error for me
Sorry to interrupt but I have a problem in my code and I need help. Can I get help next?
I just like to be polite
yeah no worries this aint a doctors office or anything lol
lol
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class Controls : MonoBehaviour
{
private Rigidbody2D rb;
private float jumpforce = 40f;
private bool engineIsOn;
[SerializeField]
public GameObject fire;
[SerializeField]
private TextMeshProUGUI fuelMeter;
public static int fuelAmount;
void Start()
{
engineIsOn = false;
fire.SetActive(false);
rb = GetComponent<Rigidbody2D>();
fuelAmount = 100;
}
void Update()
{
fuelMeter.text = fuelAmount.ToString() + "%";
if (fuelAmount == 0)
{
engineIsOn = false;
fire.SetActive(false);
}
//if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began && fuelAmount > 0)
if (Input.GetMouseButtonDown(0) && fuelAmount > 0)
{
fire.SetActive(true);
engineIsOn = true;
StartCoroutine(BurnFuel());
}
//if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
if (Input.GetMouseButtonUp(0))
{
fire.SetActive(false);
engineIsOn = false;
}
}
private void FixedUpdate()
{
switch (engineIsOn)
{
case true:
rb.AddForce(new Vector2(0f, jumpforce), ForceMode2D.Force);
break;
case false:
rb.AddForce(new Vector2(0f, 0f), ForceMode2D.Force);
break;
}
}
private IEnumerator BurnFuel()
{
for (int i = fuelAmount; i >= 1; i--)
{
fuelAmount -= 1;
yield return new WaitForSeconds(0.2F);
//if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
if (Input.GetMouseButtonUp(0))
break;
}
}
}```
?code
This is the code
that wasnt the command damnit
It supposed to stop burning fuel when I stop touching/clicking but it keeps burning
and more
it burns faster
more than likely you're running the Coroutine multiple times
Aka creating a new one each time
with each click
Yes, how I can stop it?
put a boolean or store it in a Coroutine variable and check if its null
bool is prob easiest
if(isBurningFuel) return;
StartCoroutine(BurnFuel());```
bool isBurningFuel;
private IEnumerator BurnFuel()
{
isBurningFuel = true;
for (int i = fuelAmount; i >= 1; i--)
{
fuelAmount -= 1;
yield return new WaitForSeconds(0.2F);
//if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
if (Input.GetMouseButtonUp(0))
break;
}
isBurningFuel = false;
}```
restarted the project and it worked ffs
Sometimes it be like that
you could reload the assemblies in the unity editor