#💻┃code-beginner
1 messages · Page 106 of 1
is it possible in c# to define multiple case statements at once
so say for instance im generating a random number between 1 and 5
if i get a number between 1 and 3 can i define that case in one line
if ( i >= 1 && i <= 3)
if this is how i manage my movement, how would it be possible to add force to the rb object?
or do i have to make the movement by adding a force instead of changing the velocity?
you set the velocity to a set amount so any AddForce will be overwritten. Either change how it works or have a "boost" vector3 that you add to your moveVelocity that decreases over time.
I like to do thiscs Vector3 desiredVelocity = ... Vector3 difference = desiredVelocity - rb.velocity; rb.AddForce(difference * someMultiplier);
Add a force to reach the target velocity
desiredVelocity here would be pretty much the moveVelocity in your current code
Yeah, and then tweak moveForce to your liking
It affects the acceleration speed basically
Idk I rarely see anyone suggest it, it works really well
wait why is my player falling slow now?
Oh yeah, better set difference.y to zero
At least when not grounded
So that it only affects your horizontal movement
why do you apply gravity yourself instead of letting the rbs build in gravity handle it? 😮
it has a gravityScale build in
I think that's only in 2D rigidbodies
its checking if there is any item data in the container
If your character is scaled too big then it will also appear to fall slower
It's all relative to the Physics.gravity settings. The default value assumes that 1 unit = 1 meter
i just need to change gravity for this rigidbody
not anything else
Yeah that's probably what they meant, in Rigidbody2D you can set a multiplier per rigidbody
Not in 3D
one more thing, i thought moveForce would be the acceleration, but the higher i increase it the faster the moveSpeed is, how can i have like an acceleration variable?
smaller moveForce = slower acceleration
I would rename it acceleration or something though
That's just a shrinking object that destroys itself when it's < 0 scale
It will work for the ring visuals yeah, but you need to check each player's distance from the center and compare it with the radius
To check if they are outside of the ring
You can probably tweak it a bit to use the Y too. Show what you have?
Do you understand how it works?
Also please look at how to format your code in your IDE
In the transform.position = ... line you can add the camera's Y position (multiplied by some value, maybe amountOfParallaxEffect) to transform.position.y
Hi I just tried to make a WebGL build, switching over to WebGL worked fine but then when I tried to build, it ended in build failure with these error messages:
unity is inherently a 3d engine so it will always include z
2D games are still in 3D space
can you virtual and override unity functions like start and update?
Your script "Az.cs" has using directives for UnityEditor, which is not possible when building (the editor doesn't exist in a build).
Yes
They can even be IEnumerators or async
You cant use UnityEditor class in a. build
public class Jumping : MonoBehaviour
{
Rigidbody rigidBody;
public float jumpPower = 5f;
public Vector3 moveDirection;
void Start()
{
rigidBody = GetComponent<Rigidbody>();
moveDirection = new Vector3 (0.0f, 2.0f, 0.0f);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rigidBody.AddForce(moveDirection * jumpPower, ForceMode.Impulse);
}
}
}
Why ain't my character not jump?
is the method being called ?
do you have any other scripts overriding velocity
And check the value of jumpPower in the inspector
thanks I see it now, removed it
you can also
#if UNITY_EDITOR
//code
#endif
Could a character controller do that?
you should not be mixing both
Oh, so should I not use a character controller
not if you have a rigidbody
pick one
!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.
Ah, thank you. I got some stuff to recode
private void CheckOverlap()
{
Collider[] colliders = Physics.OverlapBox(transform.position, bc.size / 2, quaternion.identity, _layerMask);
foreach (var collider in colliders)
{
if (collider.gameObject != gameObject)
{
Item item = collider.gameObject.GetComponent<Item>();
if (item != null)
{
HandleItemCollision(item);
return;
}
}
}
ResetVariables();
}
How can i grab the closest collider? right now if there are multiple in the overlap it craps out
iterate all colliders and check the distance between them, store the collider with minimum distance
Wasn't sure where to put this but I'm creating a mod for a unity game and wanted to create a ui for it. I heard about the new ui toolkit so decided to go with that but wasn't sure what the difference between these two pages were
https://docs.unity3d.com/Manual/UIE-simple-ui-toolkit-workflow.html
https://docs.unity3d.com/Manual/UIE-get-started-with-runtime-ui.html
#🧰┃ui-toolkit
Note that directly discussing about modding or decompiling is not allowed in this server, so specific help about that will be limited
guys uh why does this say "object reference not set to an instance of an object"?(which i take means this, the very thing thats doing it, doesnt exist?)
info is null
info is null
oh
DOUBLE KILL
Ah sorry, didn’t have any questions specific to modding, was just a bit confused by the unity docs
Hello I need help with coding because when I slide the camera doesn't go fully down so when i slide the camera can clip through walls can someone please help me this is my code https://paste.myst.rs/ek5xrbwl https://paste.myst.rs/jpmgiynt https://paste.myst.rs/ag82jfjo https://paste.myst.rs/luy90ydi
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections.Generic;
using UnityEngine;
public class Checkifincameraview : MonoBehaviour
bool alreadyWon = false;
{
Camera camera;
MeshRenderer renderer;
Plane[] cameraFrustum;
Collider collider;
// Start is called before the first frame update
void Start()
{
camera = Camera.main;
renderer = GetComponent<MeshRenderer>();
collider = GetComponent<Collider>();
}
// Update is called once per frame
void Update()
{
var bounds = collider.bounds;
cameraFrustum = GeometryUtility.CalculateFrustumPlanes(camera);
if (GeometryUtility.TestPlanesAABB(cameraFrustum,bounds))
{
if (alreadyWon)
Invoke("LesGo",10);
}
}
public void LesGo()
{
Debug.Log("Les goooo!!!!");
}
} ```
how do I fix these errors?
looks like a syntax error
You're missing { on line 6
see if you made a mistake somwhere
real
irrelevant question ,doesnt the ide show the error? like it wont compile unless the errors are fixed
That indeed is a relevant question 
Why a sad face? I meant your question is good
I was thinking about the same
i have no idea. i really shouldnt be coding at 1 am. does a lot to a tiny mind like mine.
im going to sleep
tysm
If those aren't underlined in your !IDE, you need to configure it
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
Say I have a transform and I want a local position such that if I feed it a Vector3(0,0,5) then I would receive a new value relative to the transform (depending on its rotation/direction) as a new Vector3
without affecting the transform itself
I think translating it and grabbing the position is probably what I want but I guess I have to translate it back which makes little sense
probably would prefer to do it with a matrix4x4
Any ides on how to stop that from happening?
Does someone know what's wrong with this grounded function
Update keeps printing air even when the player is on the ground
how could aonyone read that?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't have access to discord on my computer
I think this should fix it
ok i need to save it xD stealing
Does this work https://hatebin.com/ahepeuhakc
how do flush a variable? like make it have no value
A BoxCast does not detect any object that is inside the box when it starts. It has to hit the object, so it ignores anything it already overlaps at the start. Chances are you want to do an OverlapBox instead
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapBox.html
Set it to no value
=
"no value" depends on whether your type is nullable or not
it says its expecting an expression
But I'm trying to hit the ground and i directed the boxcast down and used a layermask
i think my thing is nullable
A BoxCast does not detect any object that is inside the box when it starts. It has to hit the object, so it ignores anything it already overlaps at the start. Chances are you want to do an OverlapBox instead
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapBox.html
Anyone?
Stop what from happening
But I'm not trying to detect the player and the player starts in the air
I never said you were trying to detect the player
If the ground starts inside the box, it also won't be detected
But it doesn't. The box cast starts at the players.orgin and is the size of the players collider
Which is square
And where is the player's origin
the ground being destroyed
I'n the air away from the platform.
Things don't destroy themselves for no reason. Presumably, it gets destroyed because you told it to
Can you show the inspector of the object with this script on it, and the inspector of the thing you're trying to hit?
I could only show the code through hatebin. I don't have access right now to discord on my computer. Il wait till I'm home to get that.
nothing in my script tellsthe bullet to destroy any thing
Then look at other scripts
If it's being destroyed, something you wrote is doing it
It doesn't just destroy of its own volition
you were right sorry
how do you make it so when you click an error you can highlight what is writing the error?
double click it should show you the line in which the error accrued
Where? In a Unity game?
in the console
double click it.
LogError can take a second parameter
i meant the gameobject causing the error
Then you single click the log message and it highlights that object
Is this a custom error or one unity provides?
it does write a GameObject if the error's associated with any.
Errors already do that by default.
i want to see what object is causing this error
you cannot.
Clicking that once should highlight the object causing it. If it doesn't, the object no longer exists
Check while the game is running, when you get that error
oh, well, it should give you a GameObject with Item.cs script when you click at the error
I feel like it doesnt always work as it should 🤔
It does, I suppose?
Is Item a script on a gameobject? Or a SO? @stuck palm
hey! was wondering what the best way to create a skybox with labelable stars?
i want for the player to be able to look at the stars, and name them as they wish
and i was wondering what the best technique to go about this would be
probably a way to vague explanation but any help would be appreciated!!!
thanks in advance!!!
when an object is created it calls start right
oh shoot this question would probably be betetr suited for code advanced
yea it does
ok so, i guess a better way to word this would be
how could i go about detecting if a player is looking at a star in the first place?
not looking for like a step by step, just some ideas u guys might have :3
how come my bullets aren't doing any damage and they just bounce of the base? base has a health script and the bullet has the damage script
How can i make my car drive in the direction its facing and not in the previous direction? Currently when i drive and then steer in a direction, my car drives in the old direction and not in the direction its facing
It should already be relative to your car's direction since you are using AddRelativeForce 🤔
With some vector math. You'd need to get the direction from the player to the star, and the direction the player is looking in. Use a dot product on the two vectors, and if it's close enough to 1, then the two directions are almost identical, meaning you're looking towards the star
its not tho
ah ok!!!!
that could help identify if a player was looking at a star
but would it work similarly for detecting if a player is looking at a specific star?
i guess jsut checking the vector rotation of the camera right?
The direction from the player to the star is for a specific star
Should i change from addtorque for the car rotation to just transform.rotation and change that?
Dont move/rotate a rigidbody with transform, use rigidbody methods/properties instead.
You can try rigidbody.MoveRotation or rigidbody.rotation just to test if it fixes it.
To me the code looks like it should work as is, though.
oh!! yea i think i understand now 🙂
thank you thank you! i was mostly looking torwards how i should approach the idea in the firstplace
very helpful :))
show code
man this is frustrating
@harsh owl is it currently rotating as you expect?
ill show you wait
Show a screenshot of this object selected, in the scene view, with the Transform gizmo visible (showing the three arrows)
using System.Collections.Generic;
using UnityEngine;
using System;
public class Basehealth : MonoBehaviour
{ public static event Action OnPlayerDeath;
public float health = 100f;
public static Basehealth Instance;
public Transform player;
private void Awake()
{
Instance = this;
}
public float AddBasehealth(float amount)
{
return health += amount;
}
public void DecreaseBasehealth(float amount)
{
health -= amount;
if (health <= 0)
{
health = 0;
Debug.Log("base destroyed");
player.gameObject.SetActive(true);
}
}
}``` Hp code ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Damagedealing : MonoBehaviour
{
public float amount = 10;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.GetComponent<Health>())
{
Health.Instance.DecreaseHealth(amount);
Debug.Log("Hit");
}
}
private void OntrTggerEnter(Collider other)
{
if (other.gameObject.TryGetComponent(out Health health))
{
health.DecreaseHealth(amount);
}
}
} ``` Damage code

Here you go
You can try to Vecror3.RotateTowards the velocity towards transform.forward @harsh owl
It's the code above
And the issue is the bullet isn't decreasing the health from the thing it's expected to?
Show the inspector of that object
Also, hang on, does everything in the project all share the same health value?
That seems... odd
no
Yes
I tweak in in th einspector
does itemdrop.start execute before the code i pointed out happens?
so what the hell 😭
Start runs before the first Update the object is alive for
Awake will run though
im getting a dumbass error that shouldnt be happening
OnTrtggerEnter might be a problem
how so?
If you're getting an error then it should be happening
I'm assuming the error is on the line with the arrow
meaning itemdrop is null
no no
the error is happening on the itemdrop being created
its saying itemdata is null
when i set it
Should be OnTriggerEnter(), Keep in mind triggers only work if the collider triggering has a rigid body
What exact line is the error on
i fixed it already now, dont worry
i already deleted the error from the screenshot i showed
i tried to run a piece of c ode from item drop that wouldnt work because start hadnt run yet
it does
So why is your Health a singleton
I don't under stand the question?
You've made your Health script a singleton. Why did you do that
Presumably you want different objects to have their own health instead of one shared script
yes
ive tried it with rigidbody.rotation now but the car is still drifting / not driving where the car is facing to
why does debugLog name every single enemy by the name, but at the end I only get the last one in loop added X times
So then why did you make it a singleton. That's the opposite of that
Bullet (Has rigidbody), Base (Has Health Script with OnTriggerEnter with Collider set to trigger). When bullet Enters the Trigger, the Trigger should detect the bullet get the damage and apply to base
No OnCollision needed
That was before you showed the video. Try what I suggested after with Vector3.RotateTowards
idk not my code borrowed from a friend
@harsh owl #💻┃code-beginner message
Thats not good. Learn dont copy and paste.
I am putting together a basic script to show how it should be done
ok
Im trying
Okay, strap in because this one's a fucking doozy. What you're running into is an annoying little prick of a problem called "Variable capture". AddInfo is defined outside this loop, meaning every iteration of the loop is modifying the same instance. Since it's passed by reference, what you're doing is adding multiple copies of the same variable to the list, and every time you change a field on it, it's affecting every copy. This can be really nasty to run into and not notice so it's good you caught this problem. What you need to do is create a new AddInfo (whatever type that is) inside the foreach loop, so each iteration adds a brand new instance to the list
This is the easiest to spot form of it, with a proper foreach loop, but if you start doing anonymous functions with lambdas this is gonna be the bane of your existence and despite knowing it exists I still end up accidentally doing this every project I make and losing days to trying to track down the source of the problem
ohh okaaym got you! Thanks a bunch!
Do you know what static does
changable methods, variables, classes?
No
where do i put errors i need help fixing
If you don't know exactly why you are using static, you should not be using it
Check this out
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Health : MonoBehaviour
{
public int maxHealth = 100;
public int currentHP;
public void DamageHP(int _damage)
{
if (currentHP <= 0) Dead();
}
public void AddHP(int _health)
{
currentHP += _health;
if (currentHP >= maxHealth) currentHP = maxHealth;
}
public void Dead()
{
Debug.Log("Wasted!");
}
private void OnTriggerEnter(Collider other)
{
Projectile bullet = other.gameObject.GetComponent<Projectile>();
if (bullet != null)
{
switch (bullet.type)
{
case BulletType.Heal:
AddHP(bullet.value);
break;
case BulletType.Damage:
DamageHP(bullet.value);
break;
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum BulletType
{
Damage, Heal
}
public class Projectile : MonoBehaviour
{
public BulletType type;
public int value;
}
Learned that the hard way lol
> Says you shouldn't just copy and paste
> Provides a solution that can just be copied and pasted
At least throw in a spelling mistake somewhere to see if they're paying attention
Read before you speak
#💻┃code-beginner message
I did read, that's what I'm referring to
This would not fit his situation if copy and pasted lol good try
can I please be so unkind and ask for a solution?
what do I type in that line 187? 😄
Can you show the code for CapturedPets?
sure, it's a list class.
Okay, cool, not a MonoBehaviour. You can just do new CapturedPets() then
What you can try is store the instantiated GO in a separate variable and check if it was properly instantiated
GameObject go = Instantiate(ItemDrop, transform.position, Quaternion.Identity);
if (go != null) Debug.Log("Instantiated!);
okaay, great, works like it should now 🙂
Really thankful for that. I were running into that problem bunch of times already and had no idea what's wrong 🙂 I think I will remember this for the rest of the time I will be working with loops. Cheers!
Maybe learning it early enough in your journey will prevent you from stepping on the same rake every freaking time like I do. Best of luck!
I'm a begginer.
I have a gameObject and I want to store as variable the sprite of the children of the gameObject. How can I?
Do you want to store the Sprite, or the Sprite Renderer?
The actual image file or the component that draws it in the game
the image file
So, what you'd want to do is make a public or serialized SpriteRenderer variable, drag in the object with the sprite you want, and do .sprite to get the sprite from it
and then I want to change the sprite with a .png from the assets (I have to load it somehow)
@stuck palm After that you can check for the Item component
Item itemDrop = go.GetComponent<Item>();
if (itemDrop != null) itemDrop.itemData = itemData;
else Debug.Log("No Item Found!);
Make sure the Item script is on the Root GameObject that you are Instantiating, if not you would have to use
GetComponentInChildren<Item>()
yes
That can be done by making a variable of type Sprite and dragging in the sprite from the assets folder
Sprite frame;
and to refear at the sprite of the Sprite Renderer of the children of the gameObject?
.GetComponent<Item>() ?
A variable of that type can hold an image file from the assets folder
if you want the sprite a renderer is currently using you have to reference the renderer
Hey, guys! Can I use Time.timeScale with IEnumerators?
You can put all the sprites in a folder and load them all at runtime into a dictionary and access them whenever with id or string
Depends on what you mean by "use with", but WaitForSeconds will be affected by Time.timeScale
Ok, so if the gameObject "OMORI" have a child called "Frame", to refear at the sprite of the sprite Renderer I have to call:
gameObject.Frame.GetComponent<Sprite Renderer>().sprite ?
what's the Load command for this?
So, how to make for example audio source to stop and play depending on my IEnumerator and yes I have that but I have the WaitForSecondsRealTime.
When I use AudioSource.stop or AudioSource.Pause on my I enumerator it doesn't pause and stop at all and I am using both wait for seconds and time.timescale inside my enumerator.
I made a dash that on hold, it adds a constant force in the orientation of the camera (so wherever youre facing), but the forcemode.force is a lot stronger vertically. idk why its like this and I commented out the rest of the movement code and it still does the same thing. How do i fix it?
Putting your sprites within the Resources folder you can use
Resources.Load<Sprite>("Sprite/Folder/Path");
OMORI > frame > Sprite Renderer > Sprite as a variable (type Sprite)
Sprite frame;
Sprite new_frame;
void Start()
{
new_frame = Resources.Load<Sprite>("Assets/animations/sprites/OMORI emotion UI sprites.png");
frame = gameObject.frame.GetComponent<Sprite Renderer>().sprite
frame = new_frame
}
```...
Sound good?
- That's not how you give a path to
Resources.Load - There's no reason to use
Resources.Loadfor this at all just make the field public or serialized and drag it in
He wants to change the image at runtime
And there's no reason to store the original sprite, you want to set the renderer's .sprite
Resources.Load won't do that either
Thats not what I am saying
right, another question (I only know Python and lua) What's the difference between public and private and none of them?
yes
public can be accessed from any other class
private can only be accessed inside this class
There's also protected which can be accessed by this class or any child classes, but its uses are limited
class is a function, right?
Im saying at the very beginning a sprite database can be made for easy reference and switching at runtime instead of drag and drop constantly, automation > manual labor
ok, so what's the error in new_frame = Resources.Load<Sprite>("Assets/animations/sprites/OMORI emotion UI sprites.png");
I don't think that's really what they're asking at the moment and I doubt they understand what you mean anyway
several
Again, that's not how Resources.Load handles paths, and you shouldn't be using Resources.Load at all for this
You can only load resources from within the Resources folder not Assets
It can be any folder named Resources btw.
I went like 2 years without realizing 
Yep, all folders named Resources, no matter what folders their children of, combine into one big mega-folder Resources for the purposes of pathing
@ionic fjord In your Assets folder create a folder named "Resources". within that folder create your sprite folder containing your sprites
Stop
They should not be using resources
Don't tell them how to solve the issue they should not be having
It's just going to confuse things more
Your way is not the only right way and from what I see instead of helping him you became a university teacher and the problem has gotten worse lol
Resources should not be used here, full stop.
And they haven't changed anything so I don't know what you mean by "gotten worse"
Im not going to argue, good luck friend
There's no reason to use Resources.Load for this at all just make the field public or serialized and drag it in
@ionic fjord Are you setting the sprite one time for the rest of the game or would you like to be able to change it to any other sprite at any point during the game
That's not the question to ask. The question is: "Do you know before running the game which sprites you want, or do you need to parse a string to get the file name somewhere"
Resources.Load should be used when the names are not known beforehand, such as something like an item_1387 or other numbering system
public SpriteRenderer frame_renderer;
public Sprite new_frame;
// Start is called before the first frame update
void Start()
{
//Getting the Animator component
new_frame = "Some How to load the .png";
frame_renderer = gameObject.frame.GetComponent<SpriteRenderer>();
frame_renderer.sprite = new_frame;
}```
Kinda?
frame is a child of the gameObj
You can't have spaces in a type name, and you should just make both of these variables public or serialized and drag them in, like I said before
like this?
Yes, now drag them in on the inspector and don't set them in the code
Assets\Emotion.cs(18,37): error CS1061: 'GameObject' does not contain a definition for 'frame' and no accessible extension method 'frame' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
frame is a child, what's the code to refer to it?
not gameObject.frame ?
None, you drag-drop it
That line of code should not be there
The only code that should be there is the one that changes the sprite
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteScript : MonoBehaviour
{
SpriteRenderer frame_Renderer;
//You can pre set this in the inspector
Sprite new_Frame;
void Awake()
{
//You can Load Sprite from File Path
frame_Renderer = GetComponentInChildren<SpriteRenderer>();
if (frame_Renderer != null) frame_Renderer.sprite = new_Frame;
else Debug.Log("No Sprite Renderer Found");
}
}
You can change the sprite of the renderer in code
how do i make it so this physics overlap box goes a little bit forward?
Collider[] colliders = Physics.OverlapBox(transform.position, bc.size / 2, Quaternion.identity, _layerMask);
You tell it which renderer and which sprite by dragging them in
If you want to set it through script its better to set up a database of sprites to choose from.
with Resourses.Load right?
transform.position + (transform.forward * someDistance)
Offset the overlap along local forward, at a specific distance
Yes but you only want this to run once during the boot up of the game. Then throughout the game you will always have the sprite available to you without calling Resources
No, just make it public and drag it in
You just drag them into a list instead of a single value
I wnat to change the sprite during the game
You're like a bad rash
If you need multiple sprites you can make an array and drag them in. No need to go overkill with Resources
tf
But you want the files to be in the game, right?
They're just starting out
yes
they are in the assets folder now
I must load them in script
No, you keep insisting you know what the right way is but you literally don't
Resources should not be used here
The OP literally repeatedly saying "Change through script" or am I just crazy?
yes
So, you'd want to make a list of sprites, and drag them in. Then you can index them by name or some sort of ID
a = b- that's how you change through script
Correct me if I'm wrong but OP does not want to use inspector
Add "a bit forward" to the position you give it, whatever that may be, Vector3.forward or transform.forward?
We are changing them through the script. They don't need to assign them in script
Making a list and drag and drop involves inspector
That's going to add a lot of needless complexity for zero gain
It's going to make the project slower, more complex, and more error prone for literally no reason
It's not for you to decide lol I'm just helping a person with what they asked for not what you think is best
Running once at the very start is going to slow things down?
They didn't ask for Resources explicitly
what are resources
No, you keep repeating "Resources" and they don't know what that means and you're just confusing the matter. They are literally trying to assign the sprite of a renderer to a different sprite and you're making this way more fucking complicated
They're new to the engine so assignment through Resources is the very last thing you'd want to suggest
You're right, they did not but they also do not want to use the inspector which everyone is trying to enforce lol
You're making it impossible to answer the actual question because you keep misinterpreting the problem and muddying the water
Inspector referencing is one of the first unity scripting subjects one should learn
they also do not want to use the inspector
Source? Link to message please
its not even complicated lmaoo.
Run Resouces.Load to grab all the sprites in a folder throught them in a dictionary/List and make a static refernce, so much work
or in alternative I can put all images in scene and make transparent those I don't want and make 1 visible at the time
But I'll prefer to change the sprite of the "frame" child
"Not even complicated" is subjective lol
I'm a begginer.
You need to adapt your answers to the experience of the user
Please stop crying everyone here it is the proof
lol what?
Set the sprite through script
And the OP refuses to drag and drog the sprite to do that so what is the alternative?
They're not refusing they don't know how to do it!
For the third time, they're starting out
To set the sprite of the renderer through code without dragging and dropping a preset sprite you would need to grab one from file path
Nobody said they didn't want to drag-drop?
I think you're mixing up referencing the sprite asset, and assigning it to the renderer
But anyway
It's okay we solved the problem in a thread pretty quick when I didn't have to spend half my time telling you to stop posting disinformation
[Diversion program ended with code 0]
This is before I even started talking to OP
Because they did not know that you can just reference them directly yet
I can see the thread and nothing was solved lmaooo you just repeated what they still dont want to do 😂 🙏
If you took the time to learn the actual problem you'd have seen that. This is beginner code, you have to learn to find the question actually being asked when people don't have the words for it yet
All I can say is OP was far more interested in my method but you kept saying no no no and force you perspective, thats cool.
Mate you have a very tenuous grip on reality. You're just straight up hallucinating interactions
Are you ChatGPT
Anything remotely complex-looking is more interesting compared to the simple stuff. That doesn't mean the complex solution is the best.
Yes you can build a whole database with a single Resources.LoadAll<T>() call, but they don't need that
I was not arguing that my method was the best it just appealed to the OP and was an alternative to what was proposed
They literally need three sprites. We solved the problem in the thread without you
I thought "they didn't want my solution" and you were the only one "answer the real question" now suddenly it's "I'm just providing an alternative"
So let me get this straight.. OP posts and didnt accept the method you propose, so I suggest something and OP is interested (in something that maybe complex to you), you yell no you dont need that no no no, and proceed to open a separate thread telling them to ignore me and whatevere and force your way onto them and Im hallucinating??? Lmfaoooo
hey i have a rigidbody controller script and everything is fine except momentum, sprinting doesnt work on uneven terrain or anything that isnt completely FLAT, which i think is because it doesnt have any momentum, like running of an edge doesnt do what you think id do, especially using a rigidbody controller.
Im moving with this playerRigid.AddForce(velocityTarget, ForceMode.VelocityChange); and i dont know where to look for the problem
The complete lack of consideration for the OP in this message shows it all. Out of touch that indeed, users can have varying experience with the engine. You may provide further solutions but to users that post in #archived-code-advanced
As it seems like you cannot adapt your answers to the level of the user that needs help
No, here's what happened:
They posted a thing they thought might have been the solution because they didn't know what to do and were trying to piece together something
You assumed that meant they absolutely 100% needed to do that exact thing and all other solutions were dumb and stinky
You proceed to derail every attempt at explaining the correct way to do anything, making explaining the actual process impossible
We take it into a thread without you and the problem is solved in five minutes
Slopes are agony with rigidbodies, particularly if you don't want them to slow down the lateral movement or have a slope limit that slides you down if it's steep enough. Depending on how you're handling the movement you might need to do some vector projection. There are tutorials for handling slopes on rigidbodies in a few ways.
ah i didnt know its a common problem, slopes itself are fine, i slide down at a specific angle, works great, just the issue you described yeah, ill google about it 
thought maybe there is something im doing completely wrong, maybe a different ForceMode since VelocityChange is a bit weird too
Basically, you can use ProjectOnPlane to get the vector along the angled plane, and use that for the force instead of just forward or sideways
https://docs.unity3d.com/ScriptReference/Vector3.ProjectOnPlane.html
It involves a lot of math
math 
This how I know you are weird because I didnt force anything on anyone. You were talking to OP for almost 5 minutes before I even said anything, when I did I didnt even mention Resources until OP asked me questions which I gladly answered, seemd like you got butt hurt and started telling me stop no no lol Im done
is there anything easier?
Get ready for vector math if you are writing your own rigidbody character controller
i feel like ProjectOnPlane is a bit overkill
its not mine, its an asset and it works well, just having issues with sprinting, i guess the author never tested it lol
Use an existing controller if you dont want to write your own. It's really not a simple task
i am xd
It's not as complicated as it seems. You have a world-space vector that you're using for AddForce already which is half of what you need. You just need to get the normal of the plane you're standing on at any given moment, then you can use ProjectOnPlane with that vector and the stored normal, and pass that vector to AddForce instead of the original one
Yeah, nothing overkill about projectonplane
oh i actually understand what youre saying
been feeling extremely stupid the past few days trying to get things done lmao
thanks man, think i can work with that ye
been using bing ai to ask for examples and explanations for certain things too, great help in learning concepts etc
Yep. The black box now is how you get the normal of the surface you're standing on, which depends on how you're doing ground checking. There's several ways to go about it but it's mostly just going to be getting the normal of a raycasthit and storing it
ik what it used for but i wanna know why we need to import this inorder for us to able to make the charchter to move
you don't, unless you want to use the PlayerInput component to control your input actions
check the docs pinned in #🖱️┃input-system to learn how to get input using input actions
so i used this and put it in code to allow me to use awsd
i already coded it
but im just want to know the purpose of that
read the docs
k ill give it a read
there are plenty of ways to get input via the input system. the PlayerInput component is just one of them
so the use of player input is to allow the user to make inputs
such as wasd
why is this error showing up, i put an animator in the script
you probably have another component in the scene where it isn't assigned.
or you're reassigning it to null in your code somewhere
so from my understnading it has 2 components where the player can make actions such as wasd and also player input manager
is the stament true?
the PlayerInput component is just one of several ways to control your input actions for your objects
yeah i accidentally had an empty version of my script in one of the children of my gunner enemy
oh ok so i import player input so the user can control my chharchter alongside some code
if you have questions about how the input system works then you should ask in #🖱️┃input-system
and actually read the docs to understand how it works
can u give me a yes or no cause i did read it but i just wanna clarify that statment
then im good
the PlayerInput component has nothing at all to do with your character. it's just a component that allows you to easily manage your input action asset and other components can react to input through either subscribing to events on it or by receiving messages sent by it.
and it is just one of several ways you can get your input to your other components. you do not have to use it
how do i block strafing in the air, like when i jump and i look to the side, the player shouldnt turn in the air
do i just calculate the moveDirection when the player is grounded?
something like that, my dir is WishDir
if hes not grounded, how can i like not half but make the player turn slower in the air
like would i just half the inputs?
moveDirection = orientation.forward * (y / 2) + orientation.right * (x / 2);
Anyway why are you moving before calling HandleGroundCheck?
so one might import it to easily manage input actions sent by the user and also to transfer input to ur other components
what do you mean
wouldnt it be the turn code?
You handle jumping, sprinting etc THEN you are checking for is grounded
Should be the other way around
order of events can matter
It does
First you move, the you chceck if is grounded
Even if it's called at the same frame, the order is wrong
And it will move even if it shouldn't for that frame
In this case it won't make noticeable difference but still a good practice to do things in a correct way
wait your on about why i have the if statement with grounded before calling the ground check method?
if thats what you mean then i know
that code is here for testing
Good example would be having OnHeal event for example in your even system and a healthbar. Imagine you are updating the healthbar via this event, but you invoke it one line above actually healing
its gonna be in a different function
The healthbar wouldn't change then
yeah i know
HandleGroundCheck should be called first
Then the rest of the methods dependant on is Grounded
how should i limit strafing in the air then?
That's not related I just left a side note
You can decrease your strafing speed or whatever if you are in air
does someone know why this is Grounded function does not work?
when the player is on the ground it should print ground but it never does.
Because the layermask is not right, or grounddistance is too small to reach from the box center to the ground
If the box height is bigger than .4, that won't reach
and what have you set as the layermask in the inspector
and are the objects that should be detected as ground actually on the ground layer?
does it have a collider
yes, a box collider
then make sure that your raycast is actually long enough
#💻┃code-beginner message
It is 1.16
I dont what you mean by your message
Your raycast is too short.
ok il try 1.16
The box is 1.16 units tall, you go from the center. You need .56 or so
it probably only needs to be like 0.6f since your player appears to be about 1 unit tall
that's the platform not the box they are using to check
Oh whoops
still though, just over 0.5f should work
but if the boxcast is the same size as the players collider then why does it have to be so big
how would i disable movement when ground pounding?
well for one, it's a raycast not a boxcast. for two, it starts in the center of your box. it needs to be at least half as long as the box is tall to reach past the edge of the box
if(!groundPounding) Move():
oh I thought I did a box cast, Thank you
Is partial MB classes strict about file naming?
Nah, just one file has to be named right
depends on your unity version
From my experience
but yeah, on 2017 you'll for sure need one with the same name as the class
you're able to add a component via the Add Component menu that does not match the file name? 🤔
can newer unity work without one?
Hey, first time here and I am also very new to Unity, I am trying to implement a life system and I am testing it now, this is the code I have but I am not getting anything in the debug log after colliding 3 times
all partial scripts are not using the name of the class
lemmetry
can addcomp just fine, ye (with 1 script following the name, and 1 using different name)
!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.
is that not what you had just tried? because the Add Component menu and dragging the script onto an object are the only places where the file name matters
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
didnt try to addcomp, i had an existing dummy class
Do you have the other object tagged as Cylinder004? Or is that the name of the object?
Show the inspector for the object with this script
It's not on a child object, right?
I have it tagged
Are you saying that filename doesn't matter if you use, say, AddComponent from a script?
okay well the file name matching the class name only matters when adding the component via the editor. and yes, in newer versions it is much less strict
#1078093315435679784 message
tried this before, it will fail on build
correct, that has never been an issue afaik since that happens at runtime
but you can add it in editor via script
what can i improve in this locomotion function
TIL, but apparently it breaks in a build 🤔 @queen adder how does it fail?
it shouldn't break in a build considering the file names just don't exist in a build
try it, i used SO's before, not monobehaviour btw
but pretty sure it will do the same problem
left is the player, right is the cylinder
now im curious, lemme try MB
You can use cached hash ints from Animator.StringToHash instead of strings for better performance
For the anim parameter names
Combine your calls into one.
Crouching is 1 when isCrouching, and it's 0 in all other cases.
animator.SetFloat("Crouching", isCrouching ? 1 : 0, locomotionSmoothness, Time.deltaTime);
Likewise for walking and sprinting. Walking is only 1 when isCrouching is false and either isSprinting is false or your speed is less than 0.25f.
Then you can just replace this entire mamoth if-else chain with three lines, each one checking its own condition
foreach (GameObject obj in nonPlaceableObjects)
{
obj.GetComponent<MeshRenderer>().sharedMaterial = currPathMaterial;
}
i have this code. it looks at each gameobject in the array nonPlaceableObjects and sets its material to currPathMaterial. I basically want each object in the scene with a certain tag to use a material. the way im doing it now is that each time i add an object in that i want to be unplaceable i have to add it to the group. this way also just seems not good for performance and inefficient. is there a better and more optimized way to do this?
so have i missed anything i could have replaced?
also no, not on a child object
Maybe modify the material instead of assigning a different one? If they all share the same one, they would all be modified.
is it a good idea to set up a state machine for a player controller or is it better to just do it normally with it all in one file.
like just change the color?
If your player controller is just moving and jumping, then it doesnt really matter what you do. If you have abilities that rely on the player not moving then yea a state machine should be better
guys how is called the key Fn in the KeyCode?
ok ty
If that's the property that you want to change, yes.
its better for performance?
The performance impact shouldn't be that big in either case, but it would be cleaner and allow you not to track every single object.
i see, thanks
Why is this giving this error?
CUSTOM CLASS: https://gdl.space/ahefapanud.cs
deriving from BASEMESHEFFECT https://gdl.space/viyusopore.cpp
I am trying to build btw when the error come, works well except when building
The error shouldn't come up because the entire class is excluded from builds with #if UNITY_EDITOR
Concern yourself with the first error before the others
hey can someone help me im super new and im trying to create a void method for the player score
im basically just making flappy bird so i can teach myself thye basics but im following an old tutorial without TMP so im having to fill in the blanks
start by configuring your !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
im using visual studio
yes and it needs to be configured to use with unity
I just added it (#if) just so I can build, it's just a random problem I have encountered
ok i configured it, now what do i do
do you see errors underlined in the code now?
UIBehaviour has them defined out. You need to as well.
yes
weird, my UIBehaviour is different
then you should see the error is underlined. remove the () from it
anyways, yea Ig I can just not override the OnVal on build
Dont need that in build
thanks! did just that, sure this will work now (hopefully)
I was in the verge of removing it(whole nicer outline) in my game
alright i'll send a picture
now look at the tutorial you are following again
You are perhaps looking at a different one
Or some poorly decompiled one
i followed the inheritance
ok it looks exactly like what i did but he used the regular text component
It says [metadata] so I imagine that means it was decompiled
show it
and do you not see how your line is different from line 15 there?
read the whole line...
because it still isn't the same
ScoreText is not a string type
ok i don't even care that i just loo0ked like an idiot thank you guys
before i configured it i did it but put TMPro instead of .text
anyway, the most important thing is you not rely on copying, try to understand why you had the error
is that from a tutorial or something because that addScore camelCase function is hideous, this aint javascript...
oh i know, i did try to figure it out before and i really do try to avoid copying and so far have figured most of it out on my own. I just use the tutorial as a guide in case something isn't workiong. I really do wanna learn how to do iot on my own
yes
public void a 
UI is a package in non-ancient versions of Unity, so the source code is just there. My project doesn't have UI in it though so I just searched my drive for the script.
u is have access to unity source? O_O
well, even when it wasn't a package, you can still get the C# source with the csreference.
when i rotate in the code it doesnt rotate nicely how could i fix this?
oh i just remembered that exist
wdym "doesnt rotate nicely"
it looks like it snaps in the pics you can see its like on the whole other side
Fix the pivot point of the sprite so it's centered where you want to rotate
does this means I cant see preproc directives in all of my F12 on unity thingies?
thankyou
ill try that
how can i add the same amount of force no matter what the mass is
omg, ig I am/will missing a lot if i dont rely myself on csreference
.velocity also ignores mass
well my problem is that when i crouch i make the collider smaller
and my player suddenly walks faster i dont know why
That worked thanks!
making the collider smaller has nothing to do with the object's mass which is a property on the rigidbody
i was gonna say am i trippin
Finally tested... @slender nymph @verbal dome it does build fine with weirdly named partial classes (and ig even on non partials), as long as you can add scripts without editor
yep, like i said the file name matching the class name requirement is only for adding the component in the editor via the Add Component menu or dragging the file onto a gameobject
where is UIBehaviour btw?
@north kiln
what is the name of the file you were looking at
It's a package in recent versions of Unity.
doesnt unitycsref follow that?
No, it's the core Editor, not packages
so ig, the only answer is, if I didnt ask here, I wouldnt have been able to solve this prob? 😭
Well, you would have been able to just intuitively know that OnValidate is not present in a build, because that's what the error was indicating
I wouldnt have been able to see that preproc dir
will note on that in the future now
thanks
Can I detect if an object with just a trigger collision; collides with another object; from the object with just the trigger collider? Or do I have to detect it from the object with the isTrigger dissabled?
It may even be a package in 2017.4, I forget when upm was introduced
VSCode probably decompiled it because it's not very smart and doesn't know where the file came from, I presume VS would have got it right. Rider definitely knows
Both objects receive the same event
Then is probally something wrong on how the colliders are placed in the hirarchy; thx
do you have at least 1 rigidbody ?
Is a ball with a rb and a collider; I want a moving ring with different parts which has a collider as the outer ring and a trigger collider as the actual inside of the ring you have to aim at to detect only when the trigger collider collides with the ball
isnt these written by unity dev?
like cant they just add a #if in these
to tell that they actually hid it in the UIBe class
What’s the difference between prefabs and scriptable objects?
sounds fine. is it not working or something ?
One's a gameobject, the other is a scriptable object
I have issues when detecting only the trigger collider and not the normal one and also when making the scripts that handle all the stuff that needs to happen to communicate with each other since they are in different parts nested in the ring itself
put the script that handles the OnTriggerEnter logic on the inner ring
But can’t a prefab do exactly what a scriptable object can do?
You just save it and manually change data
Not having a transform and components is a benefit. But yes, you could replace scriptable objects with prefabs that you just never spawned into the scene and that would work, it'd just be weird
I don't think you can instance a gameobject without spawning it into a scene, but you can instance scriptable objects and they just exist in memory.
hello,i am learning with unity
i want to make enemy to follow player, i tried some variations of code from chatgpt(i tried it on another project and it worked just fine) but now i want to recreate it in new proejct and for some reason my enemy jsut start walking into random direction and then fall down
lock rigidbody
can u show what you mean "fall down"
also should not use transform.position to move rigidbody
Moving a dynamic rigidbody via its transform 
this was done with this code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
public Transform target;
public float speed = 5f;
void Update()
{
if (target == null)
{
return;
}
Vector3 direction = target.position - transform.position;
direction.Normalize();
transform.Translate(direction * speed * Time.deltaTime);
}
}
now i am testing some new ways
why not just use a Navmesh agent
but for some reason it just doesnt work as it used to work
either looks like its falling over but you're not using forces so im confused..
public Transform target;
public float speed = 5f;
void Update()
{
if (target == null)
{
return;
}
Vector3 direction = target.position - transform.position;
direction.Normalize();
transform.Translate(direction * speed * Time.deltaTime);
}
}
this worked in my last project,but in this new,it doest work
!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.
ty
you should use AddForce if you're gonna use rigidbody
or Moveposition if kinematic
Obstacle avoidance will still be a pain, I still recommend you just use navmesh agent
Following ChatGPT's answers is a good way to walk yourself into a corner because it doesn't understand context, and then when you're in that corner it'll just start making shit up
Post large scripts as links to external sites to not spam the chat, as it mentioned in the bot
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i tried this with the AddForce,didnt work either
you have to lock the rigidbody
You still need to constrain your rigidbody's rotation
in the Constraints section of the Rigidbody's inspector
thanks,i will try that
has there been an answer to whether use GetComp or field to do a single assignment?
since after the assignment, the myanim field is useless already
meanwhile, getcomp is a runtime cost
runtimecost vs uselessfield paradox
the top one will always be faster. it's just a matter of whether you want to do the lookup or have an extra 8 bytes reserved in memory
it's not a useless field. With the inspector assignment you can reuse this script even if your hierarchy changes (such as the component moving to a different object) etc.
That's a maintainability win.
it will really just do it's thing once in its whole life
ah yeah, slight design changes is also another consideration where the serialized field is still better
It's not useless, it's literally being used right there in your code
Single-use is still use
Everything is useless after it's done being used
@rich adder https://hastebin.com/share/qoselecila.csharp
this is working
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
with some changes in rigidbody
good lol
Dont use gpt
goodluck doing Obstacle avoidance with this btw 🙂
#💻┃code-beginner message
i like it since its explaining me things in the code,dont worry,i am also learning by myself,today i am just experimenting
wait, storing any unity object in a reference field will only consume 8bytes reserved memory?
i will for sure look into it how to use it etc
a reference is 8 bytes on a 64 bit system (4 on 32 bit). this is true of all references, not just unityobjects.
note that this is the reference itself and not the underlying heap memory that is allocated for the object being referenced
yep yep, im quite aware of the second one at least 😁
I guess reference actually no taking 8 bytes only since the garbage collector will store the information of it, but pointer with malloc just the same as this, a hidden free list or whatever is used, so meaningless to include the hidden data structure
need help with a script that i got off the internet that's acting up and I'm not quite sure why it's doing the thing it's doing
ok, so, the script is supposed to
1- turn object X into object Y (works)
2- add a thing to my inventory (works)
3- place down the thing in my inventory on the world (works)
but it's also removing the replaced object from step 1
can I post the formatted code here?
!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.
ideally use link
yea'
yeah, shoot
i think i should transform objectX into objectY instead and not destroy it
instantiate creates a clone
so you're technically cloning it not transforming it
don't think you need destroy at all
uhum, uhum
in unity conext Transform is the pos/rot/scale/
so i think i should look for a way of replacing it without destroying it?
and still, how do i make the objectY not disappear?
what do you want to replace exactly?
on what?
why that's happening
i tried removing that specific part of the code but now I can't place down the object I got
the destroy part ? idk what you changed
just commented foreach (var item in inventory) { item.transform.position = dropLocation.position; item.SetActive(true); }
oh wait brainfart
dont remove that one, the destory one yes?
now the square isn't turning into a circle, but I think there's ways around it
idk what you mean by that,
also I would not use this
if (hit.collider.gameObject == objectX)
{
InteractWithObject();
}
you should make a tag or something
ohhhh right
tag the interactables
and just replace the objectX with the tag, right?
i have a box collider thats a trigger but i want it to make the player be able to go through it. ik it sounds stupid but im genuinly confused💀
you can already go through it..
its not solid
if you want to make the player NOT go trough it, make another, identical collider and untick "is trigger"
not sure why you'd do that but I know very little
they said they want to go through it
yeah ik, but like, with is trigger you already go trough it so i was thinking it was a typo
im using the gorillarig but it just stands on the box
Do we have any good resources on AssetBundles?
probuilder has mesh colliders already
you have to remove mesh collider then
are you using character controller
screenshot the scene + hirerchy
Where's the gorilla?🦍
its the rig that gtag uses
then its probably custom collision detection?
No clue what gtag is.
Right. Not everyone knows about that game. It's not a common knowledge thing.
Thake a screenshot of the box inspector.
There's the box collider. If you want to not have collisions with the box, remove it.
sick, but i kinda forgot how to replace that with a tag. What I'm doing is replace the original GameObject objectX with a GameObject.tag but that isn't working and idk how ot change the if statement either
the controller probably has custom collision detection not ignoring triggers
Indeed.
Must be your movement code then.
you apply the tag on teh GameObject then use CompareTag method
im trying to make projectiles that when spawned go towards the player and for some reason when i press play none of them move and im stumped anyone got any ideas?
Why does it look like this is the cannon script but it seems to contain the logic for moving the projectile(s)?
The logic in this code makes absolutely no sense to me
i wanted to see if i could combine the two lol dumb idea ik but i wanted to see all the same
sorry lol
If you're spawning projectiles from this cannon, why are you trying to find a reference to a particular projectile in Start()?
Why are you moving that projectile from the cannon script?
How would that possibly move any projectile that this spawns, given the reference is only acquired in Start?
Basically - start over. The projectile script should likely be the thing moving the projectile
the cannon should spawn it
sad ok
Think about the logic here
thanks
you can see this makes no sense right?
ok i learned a bit and is wondering if i can improve this to make it work. (it wont)
invalid c#
Have you considered learning C# instead of whatever this is
its visual studio
And why is that relevant at all
listen i was just wondering how i can modify it to make it work with C#
any IDE / code editor wont make this is nonesense valid c#
learn c# and write c# code
There is no modifying because this isn't code this is just words
You've basically framed your question in the form of pseudocode.
damn ok
So, you should probably learn how to detect a collision, and how to play an animation, but before all that you need to learn how to make a script at all
!learn should be your first stop
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
can you enable alpha clipping of a material by code?
sure why not
actually it may be required to be recompiled
in that case just dont decrease the alpha values (or was it increase? one way or another)
i have a poker, that takes in png texture
i render it as opaque but the edges are not well fixed
so i need to clip the edges out
using alpha clipping makes it work perfectly
why do you need to disable it
alpha clipping is not enabled by default, and the team afraid it will clash with something, so we decided do it on runtime
So I know that having a public class that extends off of monobehavior makes it editable in the editor.
Is there a way to force that with other class definitions? In my specific case, is it possible to make a lone public static class that isn't extending off of monobehavior editable in the editor?
ok
otherwise just use the alpha slider values
i just viewed how it goes
Static no, but a plain C# class object can be editable if it's a member of a MonoBehaviour/ScriptableObject
And is serializable
What do you mean by if it's a member?
Class member.
public class Example
{
private int a;
public ClassB b;
protected void C(){}
}
a, b and C are members of the Example class.
Ah ok, and what about in an instance like so:
public class Example : Monobehaviour
{
}
public class Example2 : Example
{
}
Would Example2 be considered a member?
No. It's an inheriting class.
Ah, ok
But it would be serialized/editable in the inspector if that's what you're asking.
Oh, yeah that is what I'm asking XD
Because it is still a MonoBehaviour.
Inheriting class qualifies as any of the base classes in the inheritance chain.
Right, because the inherited class inherits monobehaviour
friend, is this lau or something?
this doesnt look like a programming language at all, this looks like a hyper user friendly library on steroids
If you don't have a material you will always get magenta
magenta means missing or invalid material
making a "nothing" material?
Also #✨┃vfx-and-particles this is not a code question
ah thank
im now getting into property
you can write
private Material mat{
get{
GetComponent<renderer>().material;
}
}
instead of getting it on void start right?
aside from the misspelling of renderer yes you can do this - but it will be somewhat inefficient since it will call GetComponent every time
You can also write that property more concisely as private Material mat => GetComponent<Renderer>().material;
ok ty
so we have many scenes that will use the poker, some scene will use URP , while most of the scene will use built in pipeline
the poker is not a poker until we get into the scene that will use it, we will change the material and mesh when we load into the scene, BRP or URP materials will decide here
what i need to do , is to make sure "if material is in URP , enable alpha clipping"
- check if its URP
- enable alpha clipping if URP
this is step 1
This is a very vague question. Explain what you're actually trying to do.
This is still very vague. what does "grab" mean to you?
It means you tried to access a null reference on line 28 of your script.
the reference failed
it means object reference is not set to an instance of an object
This is gonna be the most common error you run into while learning
unity posess 3 types of render pipeline , its related to rendering
this is a huge topic
how do i fix it?
get the reference right?
you can use Debug.Log();
to check if object refer the correct one
As it says, you didn't assign your reference
assign it
nothing in these screenshots proves you assigned your reference
that would be done in the inspector
Did you read through the link?
We couldn't possibly say how to fix it without seeing code of course
no the code has nothing
the inspector is where you would assign the reference
the code simply has a variable that needs to be assigned
called myRigidbody
You have another copy of the script where it's not assigned then
somewhere in the scene (or in another scene, or in a prefab)
i fixed it
it was a missplaced ;
Now that is concerning. Is your IDE configured?
i take it back
i did infact not fix it
anything wrong with this?
Ok, I didn't see how a misplace semicolon could be relevant to the issue 😂
The line numbers are not showing. Which line is the error on?
Also, I see that the file name is "ground pound.cs" and the class name is "groundpound"
Those need to match, and you should never have spaces (or special characters other than maybe underscores) in code file names
its still not fixed😢 it says the error is on line 29
Well first things first you're lucky there's an error because I'd that code ran it'd crash unity
Second, what is the error
/\
How do you intend your while loop to ever end when nothing in the loop changes the condition of the loop
its while your in the air it keeps putting down force on you until you hit the ground
Don't use a while loop there
It is already inside a loop
what loop? you mean "while"?
Nothing in the loop changes grounded. Meaning it will add the force over and over and over until the entirety of unity crashes
Do you know what while means
i thought it kinda did
I said "while" loop.
While is a keyword that means loop over this code until the condition is met
But update is called every frame...
Just use an if
oh
i thought it was when im not grounded i get downword force onto me and when i am i dont
It DOES do that.
But it can't end the loop until you are on the ground, and it can't move you to the ground till the frame ends, and the frame can't end until the while loop ends
So the entire game will freeze and you'll have to close the program
It runs the code inside the loop until the condition is false. Only one line of code can ever be running at once. Nothing in the loop changes the condition so the loop never ends. Meaning that once it enters that loop it will be adding force until you take your Unity process out back behind the shed and Old Yeller it
how can i only show all but one decimal with float? like from showing 1.94739 to only showing 1.9
ohhhh
.ToString("0.0")
ok
So just NEVER use a while loop in update until you understand it better.
As for your issue, as digi said, rigidbody is null. You never assigned a rigidbody to the variable
It is private, so you couldn't have done it in the inspector, and you don't do it in the code you showed. So it is not done
You can either make it public and drag it in via the inspector, or use GetComponent
ok i got it now
reloadTxt.text = delayTimer.ToString("0.0"); like that?
Error CS1501 No overload for method 'ToString' takes 1 arguments
What type is delayTimer
nevermind, solved it with 'reloadTxt.text = string.Format("{0:F1}", delayTimer);'. thanks btw!
hi, planning on saving some user statistics in my game including total play time, what's the best way to keep track and save it? ive been looking at playerprefs but im not sure how to use onapplicationquit in this case
json
I know don’t ask to ask just ask but bit of a weird question, Anyone have experience with AssetBundles and how their assets are saved?
i had a feeling i could use jsons, but how would i handle the onapplicationquit? do i just add it to all my level scripts?
not too sure about onapplicationquit, may need to some await to the proccess
or save and confirm first then -> application quit
ok that sounds good, is there a way to have like a global function for handling the quit process?
could try a subscription model. Invoke save on them all, but you'll probably want to get callbacks too is the thing to make sure everyone has serialized the data. If you don't await it should be fine though but larger games that could lock up your program.
oh man im a little out of my depth there, any tutorials or like keywords i could search for a tutorial?
maybe some manager where you just collect references of types with an interface of ISave where you'd iterate through all of them and save too is another idea
what do i search for these?
Save/Load system unity usually. Lots of ways you can go about it.
alright, thanks!
do Is type checks not work on derived types of derived types?
like on microsoft the example is
public class Base { }
public class Derived : Base { }
public static class IsOperatorExample
{
public static void Main()
{
object b = new Base();
Console.WriteLine(b is Base); // output: True
Console.WriteLine(b is Derived); // output: False
object d = new Derived();
Console.WriteLine(d is Base); // output: True
Console.WriteLine(d is Derived); // output: True
}
}
but if i make a something that derives from Derived, will it not find the base anymore?
in this script im making i have if (object is MonoBehaviour) but it's not getting true for things that derive from something that derives from monobehaviour
as per the example from Microsoft, anything that derives from MonoBehaviour will return true for x is MonoBehaviour
including multiple levels of derivation
its weird because its not haha
fair
keep in mind this code is very rough right no and is more of an editor extensions thing ig but my question was generic enough to post here
can someone help me with this issue? I don't see any errors when i run the script through visual studio, only in the unity console