#💻┃code-beginner
1 messages · Page 419 of 1
screenshot?
here it is
the video doesnt show the thing on the side with the file settings,
The whole thing basically gets solved when you apply scriptable objects because now you can reference an instance. You can say A goes to B, B goes to A (looping dialogue). With what you had initially, each instance of dialogue (defined in that list) was unique so you couldnt say A goes to B goes to A, because you couldnt reference A like that. Even if identical, it would be A goes to B goes to C. Hopefully this wasnt confusing.
I wouldnt really describe what you had as segmented, it's more of just how you were creating instances that was the issue in the first case.
i dont have it in scene yet, i want to transform it into sprite so i would put in on the image object
just FYI you should use mp4 rather than mkv if you want to embed the video in discord. most people wouldn't want to download the video to watch it
also this is not a code issue
i mean i cant see this thing in the video
Ah okay, and its alright. It wasn't confusing!
oh, thx you soo mutch
get => _currentHealth;
set
{
if (_currentHealth <= 0)
{
Die();
}
}
for some reason this line of code is running in update, i only want it to run ONCE when the player dies
you'd have to share more context. but your setter doesn't actually assign to the backing field. so i assume that it remains 0 so each time you attempt to assign to it the Die method is called
let me check my other script
if (collision.CompareTag("Projectile"))
{
PlayerCombat.GetInstance().CurrentHealth -= 1;
}
im only setting it here
why do you insist on showing as little context as possible
its in an OnTriggerEnter2D function so it should only run once
right?
one would assume so, yes. but you're barely showing any context at all so how could anyone possibly guess what is causing the issue
have you even bothered doing any debugging to find out what is going on?
Yeah
I did a debug log when it hits a projectile and it only ran once
have you considered a log in the setter where your issue actually is?
at least i'm assuming that you've actually done literally anything at all to narrow it down to that being the issue
ill try that
The issue doesnt even make sense, your property is not magically associated with update at all
maybe someday we'll see all of the code so we don't have to play "make 100 suggestions until they accidentally stumble upon something that might be related"
Changed the dialogue script to scriptable objects, and now can't assign a dialogue variable in the editor. This is my punishment for using custom Editor scripts lol
Custom editor scripts shouldnt really interfere with this, assuming you're using like DrawDefaultInspector, I forgot what the actual method is called if im wrong here.
What are you trying to assign? Also I highly recommend in some form saving all those dialogue options you already had because just changing this to scriptable objects might just break everything and lose you all those components saved in scene.
when I just use the base.OnInspectorGUI(), it works and assigns correctly. I'm just trying to assign a Dialogue variable.
#↕️┃editor-extensions message
Or maybe just create a new script for the SO to hold the dialogue information, create assets and then just copy what you had in scene to this asset
I dont know much about editor scripts, just double check that you're using the right types. Maybe even try this on a new test script entirely to see if you can drag it on there
My bad, first time using a custom editor script; and forgot to write ApplyModifiedProperties at the end.
but now everything functions well
I just opened my unity project for the first time in a month, but now I got some random errors I didn't have last time I opened the project, why did this happen?
configure your !IDE and check for duplicate script
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
i want to make a game entirely in visual scripting for fun
but its gonna be so pain
ok yeah it worked, thanks!
could someone simply explain what {get; set;} does
can i use "this" keyword if i want to for example the object my script is attached too?
Are all errors equal?
this refers to the current script instance . . .
I'm getting annoyed at Unity's SplineAnimate script, because it will set the position of the thing it's animating even when the script itself is disabled.
wdym?
@hallow acorn Typically, it's used (to differentiate between) if you have a class field and a local variable of the same name . . .
oh ok
The only way I've found to make it not do that, is to not give it a spline in the first place. But that makes it call an error.
how can i destroy the object my script is attached to? is there like getComponent but for the object the component is attached to?
gameObject refers to the object the script is attached to. So destroy that
Like, are some errors allowable in a project/game.
Just use the gameObject property. Also, check Destroy from the Unity docs, it should have examples . . .
Ok ty
Accessing the gameObject property will refer to the object the script is attached to. Similar to transform . . .
If you mean Exceptions rather than errors, no, uncaught exceptions lead to undefined behaviour so it's not a good idea to not deal with them
hi, I'm trying to reposition and resize a UI button with a script, but the UI button ends up being unaffected by my script. Does anyone have experience with doing something like this?
Here is my script:
public class RTS_ResponsiveUIElement: MonoBehaviour {
[Header("Position offsets (in % of viewport height)")]
public float positionX = 0f;
public float positionY = 0f;
[Header("Size (in % of viewport height)")]
public float sizeX = 0f;
public float sizeY = 0f;
void Start() {
Debug.Log("RTS_ResponsiveUIElement.Start: called");
this.AdjustTransform();
}
void Update() {
Debug.Log("RTS_ResponsiveUIElement.Update: called");
this.AdjustTransform();
}
void AdjustTransform() {
float vh = Screen.height / 100f;
RectTransform rectTransform = GetComponent<RectTransform>();
rectTransform.sizeDelta = new Vector2(this.sizeX * vh, this.sizeY * vh);
rectTransform.anchoredPosition = new Vector2(positionX * vh, positionY * vh);
Debug.Log($"Setting size to: {rectTransform.sizeDelta}");
Debug.Log($"Setting position to: {rectTransform.anchoredPosition}");
}
}
the logs do show up in the console, and the numbers of size and position are correct; but in practice my button gets its size from Rect Transform and not from my script.
What if the exception is only in the Editor and not during runtime.
that would depend on what is causing it
Well the script that reports the error is disabled when the error happens, im honestly surprised it can even log an error in the first place.
just because a script is disabled does not mean it cannot be executed
That does feel a bit confusing, I thought it was to do with the fact that the script calls
#if UNITY_EDITOR
type code.
which might circumvent the script being enabled.
no. a disabled component only prevents a few specific unity messages from running such as Start, Update, FixedUpdate. other messages like Awake and OnCollisionXXX are not preventing from running when disabled. Likewise, any method you've defined can still be called on that object
Ah okay.
I am guessing, if you have code which is throwing exceptions in the editor but not in a build then you have code inside a UNITY_EDITOR define which is causing it
Yeah, my only confusion is that the function that the error is logged in. Is only called in the Start function.
The script I'm talking about is the SplineAnimate script
void Start() {#if UNITY_EDITOR
if(EditorApplication.isPlaying)
#endif
Restart(m_PlayOnAwake);
#if UNITY_EDITOR
else // Place the animated object back at the animation start position.
Restart(false);
#endif
}
Context: the function that calls the logError is inside Restart
I think the error should be fine, since if disabled component stops Update or FixedUpdate; then I should probably be in the clear. Since it probably won't animate outside of those functions.
hey i have a slight problem. my ship shoots barrel towards my target point, randomized by around +/-10° on the y axis. is there a not to complicated way to increase the probability for the barrels to get shot towards the middle of the island like an heatmap?
If I wanted to be really safe... I could use AddComponent to add the SplineAnimate script only when I needed it and then remove it otherwise.
could i do 2 targets, one for every island with a bit smaller rotation range and a 50/50 chance on which target it lands?
I mean, you could randomize the randomization. Like have a Random from 0 to 100, then define some value, like 50 ; if its higher than 50. Then change the random +/- 10 degrees on the y axis to +/- 2 or 5 degrees instead. If its lower than 50, then the regular +/-10 degrees.
Or if you want the accuracy probability to be more gradual. You could lerp the former solution. Like
Mathf.lerp(10,0, Random.Range(0.0f,1.0f)).
is this considered too much scripts for a game with a dialogue system and combat system and inventory system
no
kinda thought it was overboard
but you should create some folder structure for it
i already did but in VS it shows like this
in unity i have a huge array of subfolders
Heya, do anybody know how to store DoTween animation in a scriptable object please?
I dont think there is a way, you would have to write a converter, like make a list with instructions and then have another class piece together the dotween sequence
Alright, thanks will see what can I do
Simple question, how do you invert a layerMask?
thanks!
Can someone point me in the direction for how to program rain? I have a particle effect but I'm a little dumbfounded on how to randomly time the initiation of it, and when I google it I just get creating the particle effect...
which part are you not understanding how to do? like are you asking how you can randomly call the ParticleSystem's Play method?
That's baby scripts. You can have a thousand and be fine . . .
Yeah how do I implement it randomly?
well you can generate random numbers using the Random class. beyond that it really depends on exactly how you want it to behave
can i get a transform in an array using getComponent and CompareTag? if yes how exactly would the index look i cant figure it out
i want to build a game and this is coming up while building it The name 'AssetDatabase' does not exist in the current context.
{
Camera mainCamera = Camera.main;
int newPos = (int)mainCamera.transform.position.x + 21;
switch (newPos)
{
case 0:
nameText.text = "Bagieta:";
descriptionText.text = "- podobno od niego capi\r\n- lubi fugę\r\n- jako skrzydło posiada piłę łańcuchową";
twitchText.text = "- https://www.twitch.tv/mbagietson";
break;
case 21:
nameText.text = "Mamm0n:";
descriptionText.text = "- jeździ na wózku\r\n- lubi makowiec i chrupiącą\r\n- lata machając chrupiącą";
twitchText.text = "- https://www.twitch.tv/mamm0n";
break;
}
AnimationClip clip = new AnimationClip();
Animation animation = mainCamera.GetComponent<Animation>();
AnimationCurve curve1 = AnimationCurve.Linear(0.0f, mainCamera.transform.position.x, 0.75f, newPos);
AnimationCurve curve2 = AnimationCurve.Constant(0.0f, 0.75f, -10.0f);
clip.SetCurve("", typeof(Transform), "localPosition.x", curve1);
clip.SetCurve("", typeof(Transform), "localPosition.z", curve2);
clip.name = "CameraMoveRight";
clip.legacy = true;
animation.clip = clip;
animation.AddClip(clip, clip.name);
AssetDatabase.CreateAsset(clip, "Assets/" + clip.name + ".anim");
animation.Play();
leftArrow.SetActive(true);
}```
this is the code and the ``AssetDatabase.CreateAsset(clip, "Assets/" + clip.name + ".anim");`` is the line that the error is refering to
what can i do to avoid this
you cannot use the AssetDatabase in a build
is there something else i can use?
is there a reason you are creating an asset there?
so i can play it
or i dont have to create it there
i just want to be able to play that animation which is created in this script
I was thinking something akin to "every X amount of time, do a random chance of like maybe 24% or something, then rain" but I'm stuck on how to code 😅
this.GetComponent<Image>().enabled = false;
why is this doesnt work can someone explain?
break it down into smaller steps. you need to figure out just a few things:
- how to do something every X amount of time
- how to generate a random number
- how to use that randomly generated number to determine if your 24% chance was successful or not at the time you check
- play the particle system if it was successful
be more specific than "doesnt work" because there is nothing about that line specifically that wouldn't work
'Image' does not contain a definition for 'enabled' and no accessible extension method 'enabled' accepting a first argument of type 'Image' could be found (are you missing a using directive or an assembly reference
it said this
you've got the wrong using directive. you are likely trying to use UnityEngine.UIElements.Image rather than UnityEngine.UI.Image
oh yea lol tysm
i dont see that UIElements.Image before
sorry, but i appreciate your help
no problem, you just gotta pay more attention to the options in the autocomplete in your IDE, when you start typing something like Image it will show multiple options, and should show the namespace for each option, which option you select or tab to complete will be the one the namespace is imported for
thanks for the advice man
Hello,
I want to put a bubble at the top of a PNJ when I come close to it. Should I create this bubble as a child of my PNJ or create it in the canvas ?
"PNJ" is "Non playable character"?
Oh yes sorry, PNJ is in french 😭
Yes so an NPC
So bubble is supposed to be UI?
i'm making an inventory system for a 3d unity project. right now i'm trying to add a drag and drop system to the items but it doesn't work.. I only have debug.logs right now and nothing shows up in the console
DragDrop - https://hst.sh/cufazifuva.cpp
ItemSlot - https://hst.sh/movubemodo.csharp
i've read forums talking about adding a StandaloneInputModule to the event system but because im using new InputSystem i need to use a InputSystemUIInputModule. I've added a canvas group to the item, made sure the canvas has a GraphicRaycaster. I also did an Event System debugger - https://hst.sh/musobofono.cpp and still nothing shows up in console. when i click on the item absolutely nothing happens
Yes
It will be an image with some text in
But I want the bubble is fix compared to the NPC
If your npc is not UI, you won't be able to make a UI bubble its child
In your npc script, serialize the bubble prefab and instantiate it at the beginning of the game, constantly aligning its position when changed
Surely, you will have to use the main camera to convert the spaces
But how I can put the NPC in my grid if it's a UI. If my NPC is a UI, it will be in a canvas no ?
That's right, is your npc UI?
trying to recreate a system like qwop without ankleshttps://paste.ofcode.org/379dhvpMEsxaYJJxwDii8x4 I have this script but that doesnt work properly I cant go forward.Thought about it may be because of limits.(dont use animations)
No, it's just a gameobject with a box collider 2D to know when the player is close of the NPC and with a sprite renderer
Then implement my previous suggestion
So the NPC will not be a gameobject but a UI, that's it ?
No, have you read my response already?
This one yes
Yes
Mhhhh, so if I understand, I need to change always the position of the bubble UI in the script of the NPC ?
Yes
And transform it
Hello, Can anyone help me with scriptable objects?
So, I'm trying to make an editor script for the scriptable object so that it shows toggle buttons like shown in the video and I can store where obstacles need to be instantiated on the grid. But, currently what happens is when I hit play or restart unity or recompile scripts the scriptable object gets reset as shown in the video.
Below are the relevant scripts:
Obstacle Editor:
using UnityEngine;
[CustomEditor(typeof(ObstacleData))]
public class ObstacleEditor : Editor
{
public override void OnInspectorGUI()
{
ObstacleData obstacleData = (ObstacleData)target;
for (int row = 0; row < 10; row++)
{
EditorGUILayout.BeginHorizontal();
for (int col = 0; col < 10; col++)
{
obstacleData.blockedTiles[row,col] = EditorGUILayout.Toggle(obstacleData.blockedTiles[row,col]);
}
EditorGUILayout.EndHorizontal();
}
if(GUI.changed)
{
EditorUtility.SetDirty(obstacleData);
}
}
}
ObstacleData:
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "ObstacleData", menuName = "ScriptableObjects/Obstacle Data")]
public class ObstacleData : ScriptableObject
{
[SerializeField] public bool[,] blockedTiles = new bool[10,10];
}
!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 are not saving to the assetdatabase
ohh? I'm still new to this can you explain how I can do that?
look at the AssetDatabase.Save documentatioin
The ScriptableObject has to be saved to your AssetDatabase for its values not to be removed
https://gdl.space/laxiqikiga.cs hey guys some questions to solve from this code Where
What SetDirty does is mark the object as dirty for it to be saved in the AssetDatabase when the Assets are reloaded
Ahh I see I'll take a look at the documentations then
Hello, guys! I am playing around with post-processing and I don't understand why it says that to me? Also, it doesn't work when I am checking and unchecking it, I mean in Screen Space Reflections.
Well, actually, it doesn't seem like you should
The x and y of debugvelocity are always 0,0 when running. However, in the velocity of info of rigidbody2d in the running window, you can see that x and y have numerical values. changing
huh?
The object is already saved in AssetDatabase
ohh yea so why does it reset on reload?
I'm not sure yet.
ahh alright please tell me if you find something. Thank you for the help!!
Don't multiply your velocity by deltaTime, it is incorrect
The physics will take care of that
@errant anchor The value it is printing is not actually (0.00, 0.00) but some small numbers (like 0.0001), that's just how Vector logs look by default. It shows only two decimals.
RigidBody.MovePosition already included deltatime, right?
MovePosition actually does not. Only the physics methods shouldn't have it (addforce, setting velocity)
By the virtue of where it should be used
Since it should be used in FixedUpdate it will be frame independent (based on fixed frames instead)
Oh yeah right
Hmm i just changed from transform.position to Rigidbody.MovePosition and now my units are slow as hell and I am not sure what the difference is right now even though ive done it a hundred times by now xD
well the solution was just above this, forgot to switch to fixedupdate
ok got it and thx for your help
now the problem is I removed the delta time issue and it's still the same speed is 4 debug or 0
Hi everyone, I'm currently developing a video game in unity, the game is set to be released at the end of this year, but I'm having trouble setting up the procedural animation for the monster, does someone knows about procedural animations on Unity?
the velocity go to seven
Put emission into a local variable first then modify that
You cannot both get and set a struct on the same line. You want to store the emission burst in a variable, then modify it's count
I don't really understand what you are saying
Try this log instead:
Debug.Log($"Input: {inputDirection}, speed: {speed}, Rb.velocity: {Rb.velocity.ToString("F6")}", this);
this will tell you more about the input and speed values to see which is the problem
Hello, can anyone help me add nuget libraries in unity ?
Tried but it's getting removed from project
Btw {Rb.velocity.ToString("F6")} can be shortened to {Rb.velocity:F6}
As shown in the image, your Rigidbody2D's velocity is displaying values of (-4, 7), even though you have not provided any input. This is puzzling, as you would expect the velocity to be (0, 0) when there is no user input.
ok
ight u guys are genius so this should fix it right?
no errors so Ig
I have this line of code and I want it to pick a float between 0 and 1, but it constantly picks an int. how can I make it pick a float?
float spawnValue = Random.Range(0, 1);
Random.value 🙂
Provide floats as arguments so it knows to use the float overload instead of int
so is Random.Value more reliable or (0f, 1f) more reliable?
Same result
is this possible?
okay, thanks!
You can't assign to the structs in particle system, you just modify them and unity does the rest automatically
The structs are just sort of wrappers with properties
Random.value is only 0-1 float.
so its quicker to write if you you only need 0-1 (but it makes no difference functionally)
I see, so what is the supposed way to change the shape with code?
I think you are doing it right except you need to remove the last line
its weird with Particle System man... you dont need to assign back only specific things
oh that was all it was required? I see, I will try it thanks a bunch!
Any way to add? I also modified package-loci file and minefest
much appreciated on the explanation!
there is a Plugin for that
https://github.com/xoofx/UnityNuGet
Yeah particle system is doing things in a pretty non standard way in this case
I actually did not know that. Neat!
oh, thank you!
ended up going with value ^^
its funny because if you write that in VS it does give you the suggestion
Thansk
Okay, so, particle systems are really really fuckin weird in that they give a similar error to trying to modify the components of a vector, but they are passed by reference. So you just need to store it in a variable and modify it and that's the whole thing done and dusted, while the incredibly similar error with things like rb.velocity have that extra step of reassigning back. Unless you look up which things are structs or classes in the documentation, this is the kind of thing you just have to know through experience
I don't think I've ever done a string-interpolated formatter before in actual code, just when posting sample debug logs in Discord
Oh wow I would've expected you out of all ppl 😛
I see, neat explanation thanks a lot! :)
Most of the time if I have to do a string interpolation like that my thought process is "Whatever format they considered most relevant to be the default ToString is probably fine"
true true . learned this neat by accident formatting Currency or do ints as $"{sumInt:000}"
"procedual animations" in unity is pretty vague
how much procedual are walking here
fully IK ? Script driven ? etc..
yes they are not serializable
do I need a for loop to check every component of the game object?
depends what you are doing tbh
IDamageable is presumably an interface, which is not serializable by default. What I tend to do in these situations is make an abstract class that extends monobehaviour, something like public abstract class DamageableBehaviour : MonoBehaviour, IDamageable and make your script extend that. It'll still have to implement the methods, and still be an IDamageable, but you'll be able to drag it in by making that field of type DamageableBehaviour
Note, the DamageableBehaviour should not have any functionality. It's just a passthrough for the interface methods while allowing it to also inherit MonoBehaviour
I just want to access the functions that the interface provides from another script in the same game object
why not just GetComponent if its on the same object, store the private var assign it with GetComponent
oh I see
because the interface can be in different components depending on the object, so maybe if I reference the script specifically?
that defeats the point of the interface no?
If you do GetComponent<IDamageable> it will get whatever component extends IDamageable
no because it would throw an error if I tried referencing any method or is it that not correct?
As long as there's only one IDamageable on it, it'll grab that one
oooo didnt know this
thanks
If there's more than one and you need a specific one, you'll need to go either the abstract class or custom editor route to be able to drag it in
Being able to do that is honestly one of the biggest reasons to use an interface
doesnt Odin support interfaces?
Yeah iirc
I dont think I will need more than one, that would be redundant also what does an abstract class do? genuinly curious
UNLIMITED POWAAAAAH
I see that now
ISleep, IEat, ICode
lmao
It's kind of the class version of an interface. Its a class that can't ever actually exist, but can have child classes, which can override specific abstract methods that you don't define in the class itself.
yay love that comparison, use it myself. abstract is like interface but with inheritance instead of composing
For the most part, you can think of it as an interface that can define functions in addition to declaring them (since Unity doesn't support that feature of C# yet) at the cost of losing out on multi-inheritence
uu this sounds confusing for my still undeveloped uni student brain
will do some research around it, u made me curious
I just know that if I dont understand it its cuz its powerfull as heck
or just havent used it yet often enough 🙂
Interfaces are definitely the more useful out of the two, and once Unity updates its dotNET version to allow for code in interfaces they become very niche
true, I wont give up thanks for all the help
I see, how awesome!
yeah you can assign multiple interfaces to one object which can help composing a modular object.
With abstracted you are limited to only inherit one class
You know I never actually checked if Unity 6 is going to actually have that interface change yet or if that's still nebulously "in the future"
what are the reasons for doing this instead of TryGetComponent<DamagableBehaviour>? i know getting an interface has better performance but are there any other benefits?
jus want the new coreclr already 😦
I see, so cool! Ive been off of unity recently messing with C and even godot and Ive came with a more modular mentality, trying new things ended up making me learn about new stuff here so I feel like it was positive
In this case, being able to get component like that means DamageableBehaviour doesn't actually need to exist. I was assuming the reference was on a different object, but same-object you can use this instead
we need a TryGetComponentInParent and TryGetComponentInChildren 😦
had to make extension methods..
You mean default interface implementations? That's already supported. It was missing initially when C# 8 was added, but fully implemented once C# 9 was added.
However if you already have DamageableBehaviour there's fundamentally no difference, unless you're gonna need to access any MonoBehaviour methods like .transform
You mean giving it a body in the interface? It has had that since C# 9 (~2021.3)
Oh dang is it? I really should check these things before assuming they just haven't updated them
true, I always have to do a check before cant we use try catch too?
you generally dont use TryCatch in unity
unless you're doing basic c# stuff like IO writes or Web Calls
Once modern net drops I can't wait for the "wtf it supports X, Y, and Z??? What is W??? This is great!"
file record struct TempFlag;

I dont think I have ever used it but why not?
make your code more robust by not leaving any possibility something going wrong. That can't be controlled on certain things (ie writing to a file or formatting a json) for example
can i somehow get a transform using getcomponent and compareTag if yes how exactly would the syntax look like? i cant figure it out
you dont need GetComponent on a transform
You wouldn't need GetComponent to get a transform. Everything with access to GetComponent also has .transform
generally all Components have access to their Transform
(components only exists on gameobjects anyway so they always have both transform/gameobject)
Hey everyone, can anyone explain to me why my character in vibrating/bouncing when I am sliding. It works a lot better when sliding to the right, but when sliding to the left it is much worse. Here i'll show you a video:
oh ok how can i get the transform itself then?
they just told you how lol
.transform
mkv dont work in embed
yah thta makes sens ethanks
yea sorry, im working on that
also Unity components are very Weird with null checking. I see tryGet plastered everywhere it makes me cry lol
wdym should i just use compareTag("").transform??
here is the video:
this is nonsense
CompareTag returns a boolean. You cannot get a transform from a boolean
hahaha I see that makes sense
than how do i get my objects plss
What object are you trying to check the tag of
have you bothered looking at examples online
@brave compass and it still doesn't support these lol
my target points. they are used to rotate my ship towards the with some random variance
Okay, so once you've confirmed if the object has the tag you want, you can get .transform from that object
how do i know it has the tag in the code???
in order to call CompareTag on something you have to already have a reference to that object
... CompareTag
and how do i get the transform afterwards?
.transform
on the same object you just checked the tag of
its literally in the example
replace gameObject with transform its the same thing
you probably should learn how references work @hallow acorn its essential knowledge
ty i had no idea how to write it
guys, can someone help me here... #💻┃code-beginner message
I don't know why my character in vibrating/bouncing when I am sliding, especially when sliding to the left.
how can I make my character stick to the gameobject it lands on? like in crossy roads.
a common solution to that is to set the player as a child of the moving object
do you know how street address / maps work ?
thats how the . dot operator works
imagine doing Country.State.City.Address
to find your home (in this case an object, or a function etc.)
is there a simple code for that that you know or should I look it up if it takes a while
Just set transform.parent to the transform you want it to stick to
thanks ill look into it
The creature that I’m trying to animate is a spider with 8 legs, and each already has IK rig on it, but I’m having trouble with the code, I have been using this video from YouTube https://youtu.be/acMK93A-FSY?si=sqU7fCK5ghzZkscu
In this episode of the Prototype Series, we've expanded the Procedural Boss project by creating a procedurally animated walk animation!
⭐ Project Download https://on.unity.com/3jX6PAY
⭐ Training Session https://on.unity.com/3atx3rW
⭐ Procedural Boss video https://youtu.be/LVSmp0zW8pY
Timestamps:
00:00 - Intro
00:54 - Setting up the rig
03:55 -...
should probably post the code and explain exactly what the issue is with it. I personally don't know much about procedural walks, someone might
ive gotten mine to stand.. but no walk yet
took me ages just to get my character to press the button dynamically, it was not a fun experience lol
ya, its never straight forward for sure
is there something that only happens in unity editor?
how should we know you only posted 1 function
debug it
animation component is wildly outdated
why is this even going on here typeof(Transform) ohh I see because animation clip function..
wasn't Animation component deprecated or am I misremembering 🤔
anyway I have no clue what this scrip is supposed to do but cant you just use the Timeline
it's not deprecated, it's just older than the mecanim animator system and is considered "legacy"
its moving the camera to the right
ohh I see.. mandela effect maybe. I remember putting component on gameobject once and it warned me
is there a reason you need an animation to move the camera to the right?
especially since each time you call this method you create a brand new animation clip
i dont want it to just change position instantly but gradually move to the other position
sure, but is there a reason you need to use an animation for that? it's incredibly simple to just lerp its position or whatever
you can even sample an animation curve for the lerp's t value if you want easing
if you're so new, perhaps consider going through some basic courses to learn wtf you are doing. i don't understand how you came to the conclusion you needed to generate an animation clip and also save it into the asset database (since you were doing that earlier) just to move an object when almost every google search would have provided information about just modifying its position or using cinemachine or something
the pathways on the unity !learn site are an excellent place to get started learning how to use the engine
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this some type of AI code aint it?
no one said that
😄 nah, just not common
I'm all about the basics . . .
usually AI comes up with wild functions to do basic things was curious were code was from
i guess i code like ai
you copied n pasted it or wrote it line by line?
Is there a way to make it so I can check if an object is touching ANY other collider instead of just one with a pre-defined gameobjects collider?
i found it somewhere on internet when i searched how to create an animation by script
ah yes I can see why that showed up now
if its a cinematic why not use Timeline or Animator?
no scripts needed
acutally even the dolly function in cinemachine
its more rhetorical.. just giving u some options
no worries you'll get there. its trial n error
but you guys know everything about unity
I'm not sure what you're asking - that sounds like the default behavior. Unity will invoke collision messages for any two objects with colliding layers
not me personally no, maybe 25%
👍
lmao, i wish
Such a person does not exist
not even Unity Devs know about everything Unity 
I'm having a issue with my script, the point of the script is to make a mini Looking system for a stationary player, my only issue is that the yaw never starts at the cameras y rotation i set it to at the beginning. https://hastebin.com/share/vanokurude.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
for example, my player starts at -180 y the script sets the player to -90
the look max is 90
i see gimbal lock in ur future
anyone know how to make my colliders work?
I tried changing it from collider to collider2D, collision2D, collision and one other option I can't remember.
Where do you set it in the beginning?
i would not directly set localEulerAngles
i would use .rotation/localRotation instead
CameraROTY
ok
Do you have a script named Collider in your project
you should be using OnTriggerEnter2D and its Collider2D parameter
ah ok
fixed 👍
also theres an error there because ur trying to use OnTriggerEnter()
yea.. u seen nvm
the IsTouching is def not needed if it already hit Trigger
Even Unity doesn't know everything about Unity . . .
id clamp ur pitch.. then use it afterwards to construct a rotation.... then rotate w/ local like Digi mentioned
Quaternion targetRotation = Quaternion.Euler(pitch, yaw, 0);
CurrentCamera.transform.localRotation = targetRotation;```
Try this log before the clamp line:
Debug.Log($"Clamping Yaw from {yaw} between {CameraRotY - lookMax} and {CameraRotY + lookMax}, result: {Mathf.Clamp(yaw, CameraRotY - lookMax, CameraRotY + lookMax)}");
yaw = Mathf.Clamp(yaw, CameraRotY - lookMax, CameraRotY + lookMax);
ok
The first debug says its clamping from 0 which it cant so its set to -90
Then CameraRotY - lookMax is 0
Oh, wait, clamping from 0
meaning that's the default value of yaw
Maybe just give me the whole line
whole line of what?
Clamping Yaw from 0 between -270 and -90, result: -90
Okay, that makes sense. Your starting Yaw is out of range, so it gets clamped
So what's the problem?
THe problem is i need it to start at the beginning rotation. So for example my camera is set to -180, but when i enable the camera the script sets it to -90
Okay, so you should probably set yaw to the value you actually want it to start at, instead of setting it to a value you don't
It's currently set to 0
at OnEnable?
Wherever you want, just set it to something, somewhere unless you want the default value
Yes, if your script runs in edit mode. Otherwise, usually, in Awake or Start
Could store the starting yaw (euler y) in a separate variable at start, then add that to the final yaw in the Vector3 that you assign to localEulerAngles
If you want the clamping to be relative to the starting angle
I'll try this
I'm trying to access a method from a different script, I tried doing it like this (basic movement is the script that has the metod and grabTest is the accessor for hte method. anyone know how to fix this?
you need to get a reference
isn't the reference basicmovement?
access the instance, right now you're accessing a "blueprint"
That's a type
ah ok
so if I got access to the player object (which has the script) it'd gain access to the method
You need the Instance thats on the player
so if its on a player you have to find that first, or you can use a cheat sheet sometimes with FindObjectOfType(this is ideal if only 1 instance exists of said script) or whatever the new equivalent is
Wow it worked, not sure how i didn't think of this.
are you availible about the parenting issue? I made it but now I need advice on un-parenting
use the SetParent method. and to unparent it, you set its parent to null
which BasicMovement do you want
what does that mean
it means you have to tell the code What instance / version / copy of that Script are you using
u declared it (told the script it exists) but u dont assign it. (tell it which one)
imagine you want to run a function called Slap()
and say you have class named Human..
the computer want sot know, which human you want to slap ? you are looking for Jeff
I mean you could have a trillion instances of BasicMovement in your scene for all the code knows. Which specific one do you want to call grabTest() on?
no basically, my character now sticks but when it sticks it doesn't allow jumping, which is necessary to jump onto other obstacles. I tried a method to unparent first and then jump when the jump button is pressed but it doesn't seem to be working. ```void Update()
{
if (Input.GetButtonDown("Jump") && IsGrounded())
{
Transform currentParent = transform.parent;
transform.parent = null;
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
//transform.parent = currentParent;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Obstacle"))
{
Debug.Log("Crashed");
}
else if (collision.gameObject.CompareTag("Platform"))
{
transform.parent = collision.transform;
}
}
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Platform"))
{
transform.parent = null;
}
}```
the one on my player object
oops sorry mightve been too bi
if you are using a rigidbody you're in a whole world of hurt with moving platforms lol
parenting wont work well
ohh how should i change it
aka slip and slide
So, you want to reference that specific instance, store it in a variable, and then call grabTest() on that variable
there are so many videos covering this subject no ?
look up "rigidbody moving platforms" you get a plethora of info
oki thank you
Is there something like physics2d circlecast without a direction? Like just detecting whats around you? or is that just 0 for distance?
CheckCircle
OverlapCircle?
Yeah, sorry, that's the one for 2D
@silk night
yeah?
@rich adder
Please don't ping random users for no reason
set the transform.parent to null if you still need help with this
if (closest < delta.sqrMagnitude)
if (closest < delta.magnitude)
Top one is faster cause its doesnt have to calc the sqrRoot right?
Otherwise.
The bottom one is faster, because it doesn't have to calculate the square root.
A² + B² = C² (as an example, using 2D)
sqrMagnitude is the C², then you can square root it to get magnitude (or just C)
Just to be clear about the order of operations
Y'all I want to learn c# but I don't want to watch boring tut that won't teach anything for 4 hours what do I do?
lol.. that ^ or find better sources..
hopefully ur a fan of reading.. else game-dev is gnna be challenging for u
brackeys makes good tutorials
If you don't find the act of learning fun, then there's not really anything that will
the top one should be this btw, since your delta is now of a power of two (that the sqrRoot would remove)
if (closest * closest < delta.sqrMagnitude)
Are not brackey's tutorials outdated now?
no not really..
I think he recorded those way before
unity hasnt changed its basic functionallity in ages
some things change/ menus/ locations/ some things get deprecated and replaced.. but the gist of them are still the same..
i still recommend sebastian lague unity c# playlist.. its almost 8 years old
Sebastian is going too deep into maths I believe thats why he confuses me a lot haha. But yes Man knows what hes doing!
if u follow along w/ brackeys.. just remember to not multiply ur mousedelta's w/ time.deltaTime like he does in every video 😄
ok haha
I am just writing the sqr Value into the closest once i find a new closest, so i dont need to sqr it again 😄
No no I mean like some guy just looking at the screen telling me plain things that won't help at all isn't good
I need some fun stuff that won't bor me as much but still teach alot
Yk
As was suggested above, you can watch TikTok. Create a new account and make sure it only contains 30-second programming tutorials and memes
Try !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
First step is to stop thinking about it as boring. Don't concern yourself with it being "fun"
Just learn. Make your own fun after learning
If you allow boredom to hinder you, you will not succeed
if you know nothing how can you tell if it will help or not?
typo
oh
What is ActiveSelf?
Non-capital
I tried bunch of tutorials and basics and it didn't even teach nothing
Then the chances are the problem is you
follow the unity courses
Nope I followed every thing did everything correct and didn't help
lol
putting a
timer += Time.deltaTime;
in a while loop doesn't do anything weird and just makes it into a timer, right?
Nope
correct
but in update it will freeze up iirc
Most tutorials r wrong
it's in a while loop on a 'button use' function and it's instantly going to 3
actually that makes no sense without further blah blah
you need to happen over a span of frames
this will just freeze until its done
This is more or less equivalent to not having those two lines at all
oh in update()
use a coroutine
or Update
what's coroutine?
it's a piece of code that lets you "wait" in the middle of it
a special type of function in Unity
like the time.wait() in python?
not quite
Because it's a special kind of waiting
that doesn't freeze the whole application
its unitys way of doing something similar to how async works
(while not being real async)
it lets the rest of the game engine run while it waits
is this a solution? ```
Transform[] Targets = new Transform[2];
GameObject[] Objects = GameObject.FindGameObjectsWithTag("Target");
for (int i = 0; i < Targets.Length; i++)
{
Targets[i] = Objects[i].transform;
}
if(Random.Range(0, 2)== 0)
{
Vector3 TargetRotation = new Vector3(transform.rotation.x, Random.Range(Targets[0].transform.rotation.y - rotationVariance, Targets[0].transform.rotation.y + rotationVariance), transform.rotation.z);
}
else
{
Vector3 TargetRotation = new Vector3(transform.rotation.x, Random.Range(Targets[1].transform.rotation.y - rotationVariance, Targets[1].transform.rotation.y + rotationVariance), transform.rotation.z);
}
Incorrect
If a tutorial doesn't work, it is almost certainly your own fault for not following it correctly
the link I sent you has methods you can use
transform.rotation.z is nonsense as is transform.rotation.y
If it freezes the application, it should be symilar to Thread.Sleep(int)
I'm peeping that rn
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
because those are components of a Quaternion.
They are not euler angles
you can't treat them as euler angles
Because transform.rotation is a Quaternion, a 4-dimensional complex number that unless you're a PhD in math means absolutely fuck all to anyone
so what should i do to fix this?
169 people have said the same thing before you. And 169 more are probably to come. Yes this is a live counter. Yes this is only things I have personally witnessed.
"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: 169
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-07-09
transform.eulerAngles?
If you want the rotation in degrees, use eulerAngles not rotation
ok thank u
but why is just z nonsense?
they're all nonsense
oh ok thats what i wanted to hear haha
z is just the first one i noticed in your code
.rotation will give you numbers into 0-1 range
Do you know how to compute four-dimensional normalized complex numbers in 3D space?
The thing is that assigning the matrix's elements this way is not entirely correct, as they don't seem to save their values when accessed from target.
obstacleData.blockedTiles[row, col] = EditorGUILayout.Toggle(obstacleData.blockedTiles[row, col]);
You're also unable to access a SerializedProperty for a matrix with the SerializedProperty.FindProperty method, so I think the only may to do it is create your own structure with, note, a custom PropertyDrawer, not Editor, for it. This way, you also won't need to create a custom Editor for your class, assuming only this Type is meant to be drawn.
they're not angles -180 to 180
I have been using rider but shit started acting weird. Do i go with vs code or visual studio you think?
do you think i know how to compute four-dimensional normalized complex numbers in 3d space?
No, that's why I'm saying don't use .rotation
i did its in the code however jump is still disabled this is the code that corresponds to my pressing jump button while on the object: if (Input.GetButtonDown("Jump") && IsGrounded()) { transform.parent = null; rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); }
Because that is a four-dimensional normalized vector
when using .rotation to set angles, always use the Quaternion.Euler method
ok so i just delete every rotation and write eulerAngles instead and problem fixed?
Maybe? I don't know what the problem is I just wanted to explain why .rotation doesn't mean what you think it means
i dont know what you mean or like i dont think thats connected to the parenting
only when reading/setting angles really use euler
storing rotations always use Quaternions
bro i just want to turn my cannon why is this so complicated
because you don't understand it
would this work to create a 3 second delay w/ enumerators?
its not. Once you understand difference between Euler angles and Quaternion
not really, because it will wait 3 seconds before not doing anything
it is but i think i found the problem, its because of my IsGrounded method
yeah that sounds like me
ok
how do I remove the not doing anything part
That would indeed delay for 3 seconds, but it will wait 3 seconds then do nothing then end so it wouldn't accomplish much
show me the code
By having it do something
Do I put the something after the waitforseconds?
Yes, if you want it to happen after the wait
ah ok
i thought you wanted to wait for the door activate ?
are you just trying to point at a random direction between two directions?
I wanted to make it wait 3 seconds then close the door
oh ok then yeah put after the wait
this function is being called by the door activate thing
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
no im trying to make it 50:50 which direction it points and then increasing the area by adding some variance
ok those sound like two separate problems
wdym?
IsGrounded only check if my player is colliding with a ground object that has another layer not the platform layer
that must be the problem, ill fix it
you could shoot a raycast down instead
i think thats how most people do it
i think it just works better in general
i fixed it thanks for the advice
- Picking a random target
- adding some random variance to the rotation
I think you just want something simple like:
// Pick random target
GameObject[] Objects = GameObject.FindGameObjectsWithTag("Target");
int randomItem = Random.Range(0, Objects.Length);
Transform target = Objects[randomItem].transform;
// point at the target with some random variation
float rotationVariance = Random.Range(-10f, 10f);
Vector3 directionToTarget = (target.position - transform.position).normalized;
Vector3 rotatedDirection = Quaternion.Euler(0, rotationVariance, 0) * directionToTarget;
transform.forward = rotatedDirection;```
It's unclear to me why your old code was reading the rotation of the target
we don't care about the rotation of the target unless I'm misunderstanding the ask
yeah idk
Any idea why I have to regenerate csproj after opening visual studio 2022 everytime? IDE doesn't work before running the regenarate button in unity
try deleting library folder maybe and refreshing the whole project ?
delete old csprojs if any
try other new projects see if its same problem
is it just that, or do you also have to change the dropdown setting there to Visual Studio again?
Exactly
then you probably need to delete the .sln file as well
ohh thats weird is it not saving the settings?
if that is the case then unity is for some reason unable to write the setting to the registry. if you launch it as admin, change that setting, then relaunch without admin permissions that setting will stick
neither of those steps you've tried are relevant to the actual issue
Hey so I'm new to the programming thing with Unity, currently I'm trying to make a Save System for Character Creation, I want it to be Artist Friendly without needing to touch code and it's set up, the only problem is, nothing saves.
What I want to save are mostly the Blendshapes on the Character Body and the Prefabs that attach during runtime, but no matter what I do nothing seems to make it save anything.
Thanks, it worked by using all 3 steps, running as admin and deleting libary & sln. Just did all at once and it worked.
if i want to use the Vector3.Lerp and move the object smoothly i probably would need to place it in the Update() or can i try with a while loop inside another function which executes after clicking a button
Coroutines or Update
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Not like this . . . 😭
What do you mean?
He means if you want people to look at your code, post it correctly
How do I do that?
there is a bot message right there
Ah okay, I'll try it that way.
and if it wasn't clear, you should be using links to a bin site, not the inline code section
guys what is the more optimize way for read a code frame frame
ı mean like fixedupdate reads 50 frame each second
but ı want some funcıon reads 5 frame each second
can you explain wtf you mean by that
Do you mind elaborating a bit because this makes no sense
be careful wıth your words
You could use a timer
ı mean ı wants some new update functıon but it works 1 or 10 frame each second
use a timer
ı know it thıs can be or couratıne ıs a optıon too but
isnt there any other way right?
no way you can be sure to run for 5 frames/second you can only approx it
yea ı need to do ıt approx
coroutine is favourite
just ı want to know is there any way to make more slow functıon lıke update
yea ı love ıt
if I use a static class, can I access the methods from that class in any other class?
Yes
Via the type of course
Mathf.Max
Oh wait, is that the weird one they made a struct?
naturally they do need to be public
That's a static function in a struct 
Yeah just remembered. Picked the worst example of course
is there a static class thing on the unity website, I can only find it for game objects (so I can figure out what I'm doing with it)
wdym by "static class thing"
gimme a sec I'll try to find an exmaple
to create a static class you declare it as static in the code
Well, a static class is more c# than unity
it is not the same thing as making a gameobject static
yeah idk I'm just trying to figure out how to solve the CS0713 error I got
What is the actual error
Static class 'Control' cannot derive from type 'MonoBehaviour'. Static classes must derive from object.
you cannot inherit from MonoBehaviour or any class for that matter if you are making a static class
ik but then what do I put there
Just NOT static, or NOT monobehaviour
Don't make it a MonoBehaviour
You can write a class that doesn't inherit anything
public class MyClass { }
note that if you need this attached to some gameobject for any reason at all then it cannot be a static class because it must derive from MonoBehaviour
it inherits object
I'm just gonna find a video to explain static classes
answer this: why do you need it to be a static class
Sharing variables with getters and setters
that has nothing at all to do with being a static class
damn man
Or maybe have u ever thought if it's out dated
Unless it has to do with networking, render pipelines, or post-processing, it's probably been the same for ten years
Yes I have. And that would be an incorrect assumption
a static class ensures that there are 0 instances of that class and that all of its members are static.
explain the actual use case for what you are trying to do and a proper solution can be suggested
How about you shouw an example? Show your code and the tutorial that "doesn't work"
It would have to be VERY old (unity 5-) to be so outdated it is useless, and even then, it would just be different api calls most likely, so still useful. So yes, still your fault
I made a speed variable for my class, "basicmovement" and I'm trying to share it between "Phone" so I can change it whilst the phone is activated.
Then Phone should reference an instance of this class and modify that instance's basicmovement
you need a reference to the instance. you do not need static anything to be able to access variables on other objects
do not abuse static just for easy referencing
I'll give it a try
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Hey guys. Can you tell me why the code is completely highlighted in red in the upper right corner? It seems to have written everything correctly, but it is still highlighted in red.
All those red lines have errors in them
As you can see the red underlines in the code itself too
In another project, everything is fine, although it is written the same way
Is this on an older unity/C# version?
No, on a new one
The one with errors is a newer version?
In any case, look at the errors and show us
And share the whole script !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i do want to point out that if this did have errors, you wouldn't see them underlined in red because this visual studio is not configured for use with unity
So the whole problem is that Visual Studio is not configured for Unity?
i never said that. i said that your visual studio is not configured so it won't show errors
Understood. And how can you tell me how to set it up?
!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
also actually providing any information about what the errors are would help determine the actual cause of them
i have a theory, but you'll need to actually confirm the errors to confirm whether my theory is correct
Of the main problem, I can only highlight the fact that I have only screenshots on my hands.
wdym you only have screenshots? do you not have the unity editor open to actually see the errors in the console?
Specifically, the project with these errors is located on another computer, to which, at the moment, I do not have access
well then come back for help when you do have access
Hey guys i need a little help im trying to make this thing in unity shoot 4 bullets in different directions based off of what directing the shooter is facing but they all seem to go into the same direction i tried looking on google and couldnt find anything. here is the script https://gdl.space/fihatavuye.cs
I don't see anything in this code that would shoot more than one bullet
its put on all 4 shooters
also consider not using the rotation values at all for the force, and instead use either transform.up or transform.right depending on which direction they are supposed to face
also
if (timer >= 2)
{
timer -= 2;``` would be more correct
EnemyGunPos.transform.rotation.z < this is nonsense
transform.rotation is a Quaternion
you will only get a value between -1 and 1 from this
so yeah they'll all basically shoot to the right
why wouldn't you just do
rb.AddForce(EnemyGunPos.transform.right * BulletSpeed, ForceMode2D.Impulse);```
why get angles involved at all
even if you wanted an angle here and had the correct one... you were applying it to the y part of a direction vector? It didn't make any sense at all as you had it
You could also just do:
rb.AddRelativeForce(Vector2.right * BulletSpeed, ForceMode2D.Impulse);```
wait so are you saying this fixes it?
that will at least make it go in the correct direction instead of a nonsense direction. at the moment though you have nothing that makes them point in different directions
i have them rotate around this circle
Hey, I've looked around, but I need some advice. I'm trying to detect a change in a variable (mouse position for context but it'd be nice to know what to do generally) that will need to be called every frame, what is the best method of detecting a change in this variable?
use a property with an event being invoked in its setter. only invoke the event when the value is different. then you just assign to the property and it will invoke the event so anything subscribed to that event will be notified of its change
Okay, gonna have to look up a lot of that terminology, but thats a good starting point, thanks I'll try it out
I wouldn't have recommended a thing that doesn't work
Movement is null
You have an instance of this component where movement is not assigned
Hey everyone, i need a little help with a editor script. i'm a beginner on unity and C#, but experienced programmer
My problem is in this print.
I tried make a editor script on unity and need use a class MonoBehaviour, but cannot use this by missing reference, error: The type or namespace Interactable could not be found (are you missing a using directive or an assembly reference?)
Editor script: Assets/Editor/InteractableEditor.cs
MonoBehaviour script: Assets/Scripts/Interactable.cs
where?
how do i do that
Go to the hierarchy and use your keyboard to type it?
Not sure which part is not clear
I don't know where the hierarchy is
The hierarchy shows the names of th things in your scene, and their relations to each other. It is on the left by default
on unity or my code editor
Unity
it only shows my player object which contains the basicmovement script which is being accessed through the Phone script
Close VS, then in your file explorer go to your project folder and open the .sln file from there
Worth trying
Show the inspector of the object
You should really learn what the windows in the unity editor are called
Show the inspector of the object
Google Unity Inspector and show us the inspector
You should search for t:Phone actually
oh
This does not have Phone on it.
GetComponent only finds components on the SAME object
Also movement is private so it doesn't show in the inspector
Unless you specify the object beforehand
i don't have a .sln
I'm still confused, what am I doing wrong here?
I used an object reference n' stuff
As I said, Phone is on a different object
So your method is not going to work
You have an object with the Phone component on it that doesn't have a BasicMovement component on it
@summer stump You told them to search for BasicMovement which probably confused them
You're setting movement to the BasicMovement component from this object
Yeah, I get that. But that was the only thing that made sense to search for at the time
How does that effect the accessing of basicmovement
Because you set movement to the BasicMovement component on this object
Ah true, just noticed the GetComponent and private variable
if you wanted to get it from a different object you should reference that one
oh
You're showing the object with the basic movement component whereas they're asking for you to show the object with the Phone component
oh ok
What is the hotkey called where you want to skip a line without bringing everything in front of your current placement down to that line as well. Example
"He
llo"
Show your External tools settings
You mean how to add a line break in a string? \n
So regenerating project files helped, did you restart Unity and VS after that?
The object with the Phone component did not properly reference a Basic Movement component and does not have a Basic Movement component thus the Get Component call returned null to be assigned to movement on line 10. Best practice would be to reference from the inspector when possible.
I'd like to move down a line without bringing everything down with it. Like if i press enter, it'll bring the "llo" down with me, when i just want to go down
Like, in an IDE?
press the down arrow
The arrow key is so far away from my other fingies though! Theres not a closer hotkey?
- no errors on console of unity
- same errors on VS
- simple code not working
my pinky cant reach while im typing quickly
If you can reach enter you can reach the arrow keys
Turn on Numlock and use the numpad arrows 🧠
But the numpad is further than the arrow keys 😔 - assuming home row.
Closer to the right hand though lol
quick question, can I have script 1 with public IEnumerator method StartGame() and in script 2 call script 1.StartCoroutine(StartGame())
I'm mostly joking here, using that feels horrible
I use arrow keys with my right hand, at least
I use my my pinky to reach the enter key while my other fingers can type, in order to hit the arrow keys id have to reach over and stop typing in order to reach it!
I can't help you further, I don't really even use VS
looks like the assembly-csharp project is unloaded, that will need to be right clicked and loaded with dependencies. that should fix all of this
You could but it would be poor practice on my opinion. It's usually best to have each MonoBehaviour start its own coroutines, since their lifecycle is tied to the object where StartCoroutine was called. Better practice would be to have a private coroutine which your public function starts
oh, what you use for scripting in unity?
Visual Studio Code. VS had some horrible performance issues for me, at least in large projects
genius, thats it
loaded the project with dependencies
thanks guys @verbal dome @slender nymph
Thank you!
https://hatebin.com/glltpggfdy On line 42 it says index out of range exception. I have my Slots set up in the inventory. I can switch between my slots using my keyboard just fine but it throws the error.
I am kind of confused
Add this line before it:
Debug.Log($"{gameObject.name}'s inventorySlots is of size {inventorySlots.Length}, newValue is {newValue}");
And show what it says
It should be of size 4 all the time no? Why is it 0
I am following a tutorial btw
I figured it out 🙂
This is where I keep them
You have two copies of this script
Do you have another InventoryManager in the scene?
I do indeed. How did you notice?
Well, one log says it has 4 slots and the other says 0
Ah okay that fixes it. I copied another project which Ive been working on saving scriptable object data. I must've forgotten to delete that. Thanks a lot.
I thought i was actually removing stuff from the array
You can't remove things from an array
they're fixed size on creation
I think I already have with the pong
Show code show tutorial show error
It's night bro
3 am to be exact
It didn't work cuz the ball didn't return
Then why didn't you reply to me five hours ago
I was out
Bad user
They all blame the tutorial
I showed you my counter.
169 times it has been the user. Five times it has been the tutorial
Tons of ppl said the same in the comments btw
And three of those five were the same codemonkey video
Not code monkey
wait code monkey bad?
Right but the chances you've found one that doesn't pales in comparison to the chances you did it wrong
I have literally been tracking this statistic for years.
I'd love to add more examples of times the tutorial was wrong
but at this point, that just doesn't really happen
Ok discord addict
Code Monkey not great and often leaves in mistakes they fix later in the video without mentioning
All I came on here to do was find out what was wrong with the code
Ahh okay. I'll keep that in mind.
So there will just be a cut where the code is different and they never mention the changes
Okay, so post it and we can
You haven't ever done that
you've just said the tutorial is bad and never followed up
I said I followed the tutorial and it didn't work and y'all kept going on and on about me not following it
We also said to show your code and what the tutorial was and you never did
I did
okay, where is it
U gotta scroll up on the other channel buddy
You can share it more than once.
somewhat code related and im a beginner, how hard is it to use a compute shader?
To use one? Not too hard. To make one, pretty complex
After I set the tag it still didn't work
seems like part of the algorithm im working on will be to heavy for the cpu and saw that compute shaders were perfect for those tasks
Intermediate I'd say. What do you need it to do?
All right so show the updated code and what the current error is
I checked all codes 10 times
Share the code and the tutorial
Already did
It's 3am not showing that shit again late at night buddy
Then stop talking and leave until you can
havent finishbed the algorithm yet, but it will take all fluid cells and check their neighbours fillAmount and pressure to decide in which way to flow
And you said you can't 🤷♂️
That is a really dumb response.
You can link if you want but I am not scrolling through a ton of posts just to find the one from the person demanding help
When you want help, post the code and the tutorial. Until then, leave
Yet you've got plenty of time to sit here and complain
Yup this GC ain't helping nothin
If it's too late to solve the problem then it's definitely too late to bitch about how you can't solve your problem
Well, there's some extra complexity when you need to read the neighboring cells in parallel, but it you should be able to find lots of learning about that online.
Compute shaders are pretty fun, but no one can really judge if it's above your level or not
If you ever wrote shaders then it might feel a bit more familiar
only shadergraph, but ive seen they are way more suited for more complex algorithms. or too heavy for the cpu at least so i think its worth a shot at least if its not too advanced
Also knowing C# helps a bit, there's some similiarities
I'd say give it a try 🤷♂️
will do👍
is there a specific channel for compute shaders if i cant figure something out?
Probably #archived-shaders but #archived-code-general / #archived-code-advanced might be fine too
allright ty
isn't this how you make an advance for loop (i : array)?
no
Not in C#
man
that's java foreach syntax
oh it's more straight forwards
you want either:
foreach (GameObject obj in beanArray)```
or a regular for loop
c# is so similar to java except when it decides to be randomly quirky
Actually foreach loops are pretty recent for Java so it's java that decided to be quirky
i have a step offset for a rigidbody controller i have and it works fine going up the steps, but when i go down my character kinda just floats off, any ideas on how to detect if my character is going down the steps?
I would recommend, if at all possible, just using a flat ramp collider instead of actual step shaped colliders
it greatly simplifies things
i know of that and i probably will for some parts of my map but i do need the stair code for other parts
It's also quite common, even in big games
How are you currently detecting going UP steps?
a raycast is right where the "foot" of my character is and if it detects a step my character goes up it a bit
currently only if you are walking forward
is this even related to the steps? Sounds more like you aren't projecting your movement to the floors normal which would have you move downwards with the slope
oh sorry, if it is steps then this is different
Hope this makes sense...
Will a function stored in a variable be called when the variable is passed into another function call?
theres no slope
can someone explain what the maxDistanceDelta means in regards to the Vector2/3.Movetowards?
A function stored in a variable will not be called unless you actually invoke it
The maximum distance to move in one call to MoveTowards
Okay so topCard wouldn't update when it's used within MoveCard?
Transform topCard = deckManager.GetTopCard();
MoveCard(topCard, players.GetChild(targetIndex).Find("Player").Find("Hand"));
oh so like how large the step is towards moving object
What does MoveCard do
Yes, but if that distance is greater than the distance remaining, it will just go to the end point and stop
that isn't a problem, thanks
Just reparents the chosen card (topCard), to a new parent ("Hand" in thise case)
void MoveCard(Transform card, Transform toParent) {
card.SetParent(toParent, false);
}
Also, nothing here is storing a function anywhere
These are all just normal variables that hold objects
my bad i was thinking of something else, you could also snap the player down but i just wouldnt go for steps at all if it can be avoided as others wrote. This snapping down behaviour would be tedious. On small steps it'd look the exact same to just fake the stairs, on large steps it'd look unnatural
Kinda confused by that, sorry
This is GetTopCard()
public Transform GetTopCard() {
return transform.GetChild(transform.childCount - 1);
}
brb gonna figure out how to properly send you code, been awhile since I've been on here
yeah i have the snap code in place, all i need it to detect if im moving down the stairs
wait
!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.
Thanks!
This is a function that returns a transform. Your question of "Storing a function in a variable" is not happening anywhere in what you've shown
void DealCardsToAllPlayers(int cardsPerPlayer) {
CountTotalPlayers();
Transform topCard = deckManager.GetTopCard();
int startIndex = FindStartingSeatIndex();
int dealerSeatIndex = FindDealerSeatIndex();
int targetIndex;
//repeats as many times as cardsPerPlayer
for (int c = 0; c < cardsPerPlayer; c++) {
targetIndex = startIndex;
//gives each player a card
for (int p = 1; p <= totalPlayers; p++) {
if (targetIndex < totalPlayers - 1) {
MoveCard(topCard, players.GetChild(targetIndex).Find("Player").Find("Hand"));
targetIndex++;
} else if (targetIndex == totalPlayers - 1) {
MoveCard(topCard, players.GetChild(targetIndex).Find("Player").Find("Hand"));
targetIndex = 0;
} else if (targetIndex == dealerSeatIndex) {
MoveCard(topCard, players.GetChild(targetIndex).Find("Player").Find("Hand"));
break;
}
}
}
}
This is the full function that I'm using MoveCard in.
I'm trying to pick a new "topCard" from the top of the deck, each time it's dealt to a player.
Then you should probably call GetTopCard more than once
void DealCardsToAllPlayers(int cardsPerPlayer) {
CountTotalPlayers();
Transform topCard = deckManager.GetTopCard();
int startIndex = FindStartingSeatIndex();
int dealerSeatIndex = FindDealerSeatIndex();
int targetIndex;
//repeats as many times as cardsPerPlayer
for (int c = 0; c < cardsPerPlayer; c++) {
targetIndex = startIndex;
//gives each player a card
for (int p = 1; p <= totalPlayers; p++) {
if (targetIndex < totalPlayers - 1) {
MoveCard(topCard, players.GetChild(targetIndex).Find("Player").Find("Hand"));
targetIndex++;
} else if (targetIndex == totalPlayers - 1) {
MoveCard(topCard, players.GetChild(targetIndex).Find("Player").Find("Hand"));
targetIndex = 0;
} else if (targetIndex == dealerSeatIndex) {
MoveCard(deckManager.GetTopCard(), players.GetChild(targetIndex).Find("Player").Find("Hand"));
break;
}
}
}
}
Right now you're storing a reference in topCard and using that object for every MoveCard that happens
Like so?
wrong copy/paste
my bad
Find method 6 times in a double for loop 💀
Edited this with the code I meant to send
Yeah, I'm going to clean that up lol
You better do. Fine for prototyping but not a great design choise long term
Whenever you call GetTopCard() it will return whatever thing that function gets and store it in the variable. It does not matter what you do with that variable afterwards. GetTopCard() is only called when you specifically call it
I'm still beginner af, this project is just practice at this point. I've been on and off with unity though for a few years so sorta know some stuff but in bits and pieces
Okay, yeah that makes sense. That's why I was originally asking if it would be called when the variable is used or if it is only called when it's assigned. But you confirmed that it's only when it's assigned. Thank you!
It's only called when you call it. The assigning doesn't matter.
A line that's just GetTopCard() would also call the function, even though you don't store the result anywhere
Everyone started somewhere. Just as a general tip it's always good to avoid using the Find methods since there's always a better way to do it. Relying on object names is always prone to errors and has it's performance impact as well which in your case likely isn't that big of a deal
Yeah, I guess I was seeing the variable as being a way to "copy and paste" GetTopCard(), but I'm realizing now that it's just calling it the one time and storing the return value, then it's "copy/pasting" the value, not the function.
Okay good to know! I'll look into it and see what I can do to refactor(?) the code.
My goal with this is to build a poker game prototype that holds the basic foundation to make a card game mobile app, but I know the latter is far away.
Like eventually I wanna make a full on casino game, but again that's a future dream
I just started today and i could have gone better. Why does it not find follow the object? Anything wrong with the code or have i doen something wrong in Unity?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hode : MonoBehaviour
{
public Transform Kropp1;
void Update()
{
Vector3 targetPosition = Kropp1.position + new Vector3(0.0f, 1.0f, 0.0f);
transform.position = targetPosition;
}
}
where you put script? did you verify its running ?
Yeah its running. In the console it says that i have to do something with the Inspector.
What does if(collision.collider.gameObject.CompareTag(‘’something’’)) check? Does it check if the tag of my gameobject is something
Null reference exception you probably didn't assign Kropp
thats not how you write it
CompareTag is a function
Ohh with pharanthesis right
