Author Topic: Do any of you code for your jobs?  (Read 17919 times)

0 Members and 1 Guest are viewing this topic.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #300 on: April 21, 2022, 03:31:55 PM »
Going back to the first thing about putting the speed/direction on each belt and grabbing it from the belts on collision. I did some testing and idk why I thought this didn't

void OnCollisionEnter2D(Collision2D other)
    {
    SpriteRenderer srp;

        srp = other.gameObject.GetComponent<SpriteRenderer>();
        srp.flipX = true;

    }

Seems like I can getComponent on collision no issue.

Will make a script I can attach to each belt with direction & speed.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #301 on: April 21, 2022, 05:13:59 PM »
Alright, finished all the coding side stuff for the conveyor belt.

Grabbing the speed & direction off the surfaceeffector2d when colliding, which also lets me just drop crates or any non-player object on the belt and the surfaceeffort2d takes care of it.

I changed the update() code to this

Code: [Select]
private void Update()
    {
        UpdateMovement();
        if (Input.GetAxisRaw("Horizontal") != 0 || isGrounded())
        { UpdateAnimationState(); }
     
    }

And it fixes the turned animation when letting go of a direction when jumping against a belt force.


Now I need to

1) Make/find a conveyor belt texture

2) Adjust the colliders. When I put a sprite in instead of the blank square I'd been using it messed that all up.

very, very close to finished with this one environmental object.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #302 on: April 21, 2022, 06:48:58 PM »
Been coding some creative stuff to flesh this out. First time trying to write scripts that call methods from each other. Trying to figure out what I'm doing wrong here?

Code: [Select]
public class Switch : MonoBehaviour
{
    public bool ON = false;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        { ON = !ON; }
    }

    public bool CheckOn()
     { if (ON == true) { return true; } else return false; }
}

That is a switch for turning belts on/off externally (also making a reverse direction switch after I get this working)

Here is my belt code that is trying to call CheckOn() to see if the switch is pushed on or off at the moment:

Code: [Select]
public class BeltScript : MonoBehaviour
{
    [SerializeField] private bool On;
    [SerializeField] private GameObject OnOffSwitch = null;
    [SerializeField] private GameObject ReverseSwitch = null;

    private Switch OnOff;
    private Animator anim;
    private SurfaceEffector2D suf;
    private SpriteRenderer sprite;
    private float beltSpeed;

    // Start is called before the first frame update
    void Start()
    {
        suf = GetComponent<SurfaceEffector2D>();
        anim = GetComponent<Animator>();
        sprite = GetComponent<SpriteRenderer>();
        OnOff = GetComponent<Switch>();

        beltSpeed = suf.speed;
       
    }

    // Update is called once per frame
    void Update()
    {
       
     
            Debug.Log("On = " + OnOff.CheckOn());
            if (OnOff.CheckOn())
            {
                suf.speed = beltSpeed;
                if (beltSpeed < .1f)
                { sprite.flipX = true; }
                anim.enabled = true;
            }
            if (!OnOff.CheckOn())
            {
                suf.speed = 0;
                anim.enabled = false;

         
            }  }}

I drop the Switch gameobject in inspector into the On/Off gameobject field. It should be grabbing the Switch script component from it. Not sure what I'm missing to call the method.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #303 on: April 21, 2022, 07:12:22 PM »
Got it!

OnOff = GetComponent<Switch>();

was supposed to be

OnOff = OnOffSwitch.GetComponent<Switch>();


Now I can run stuff in other scripts without collisions or triggers. Cool. Will be helpful when I get around to writing my first GameManager script.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #304 on: April 21, 2022, 07:18:46 PM »
Quick question,

If I want switches and stuff to only activate when colliding with feet, do I basically make a gameobject and attach it to the player called "feet" with a feet box collider and then tag it feet and use that with these objects like standing on buttons? (and put their collision boxes off the ground a bit so running into it won't trigger with ground feet)

I still have an issue here because the conveyor belt collision is within the playermovement script and set to activate on collision with player. Is there I way I can re-write this in the player_movement code to stay Entercollision w/child 0 or something? Seems like it'd be a pain in the ass.

I was using boxcasting to detect when on conveyer belt with feet with 2 conveyor game objects on top of each other, one with a layer ground, one with a layer conveyor. But by using tag conveyer w/layer ground I don't need the double objects. But I can't boxcast with the tag so I have to base it off collision with the tagged object.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #305 on: April 21, 2022, 08:03:05 PM »
I think I took care of all that. Have the ground checks separate in feet and reporting back to the body player_movement script.

Basically everything works perfect at this point. Working conveyors, can switch them on/off, can reverse them. Set the speed and direction per belt.

Have a weird glitch where somehow my client gets pulled up the left vertical side into the air upon contact with the surface collider. Despite the surface collider having no effect on anything else.

Pretty sure this is because I don't mess with y.velocity and it's basically on default RB which is what 2d surface effect effects.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #306 on: April 21, 2022, 09:24:38 PM »
Man, I think I was just coding logic stuff for like 8-9 hours straight. Brain is broke. Probably need to take a day off this to refresh. I am ready to build out my conveyor belt challenge room next. Everything is good to go. Actually programmed my way out of this. Learned a lot of coding stuff along the way and getting to the point where I'm writing scripts from scratch with no reference and it's mostly going ok for this kind of stuff. Feel like I'm past the intro coding hump and into the beginner level coder stuff.


Only other weird thing I ran into was I had to separate on/off and reversal switches on conveyors because the on/off switch would store the speed of the surface effector and turn it to 0 and then when turning on would replace the speed.

But if I was reversing the speed with a reverse button it would conflict with the stored speed. I'm sure there's a way to logically deal with this but I'm too burnt out at this point so I just made two different scripts with 1 button you can link, either an on/off switch or a reverse/forward script. That should be plenty for a challenge room with preset directions and speeds and the ability to jump on buttons to change them up.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #307 on: April 22, 2022, 01:17:17 AM »
Have a weird glitch where somehow my character gets pulled up the left vertical side into the air upon contact with the surface collider. Despite the surface collider having no effect on anything else.

Pretty sure this is because I don't mess with y.velocity and it's basically on default RB which is what 2d surface effect effects.

Fixed this in like 30 seconds by just adding a THIRD box collider on this thing  :lol and having the side edges be further out than the inner surface-effector box collider so you don't touch that except on top.

Basically.

1st box collider is the physical box object collision that does nothing
2nd box collider is the 2d surface effort collision on top that moves non-player objects and sends speed & direction to player movement
3rd box collider is the trigger that goes a bit above that and actually triggers the collision to tell the player it's tag.Conveyor and to apply the special movement script with values sent by the 2nd box collider.

Looks really nice and clean when playing! It's...interesting building these things. Feels like engineering.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #308 on: April 22, 2022, 03:30:32 AM »
So I spent the whole night on clean up.

Went through every C# code I wrote in this project and went line by line commenting on them, taking out any redundancies and just making things better if possible. Basically fixed every issue I have through careful cleanup and logic.

Now have a really good prefab for belts, can also use it for wind stages or it's a good base for power-ups (thanks to Great Sage's timer setup code). Have really good stomp switches both for turning things on/off on jumping on them, or in the case of a belt flipping it's direction.

All the collision codes and trigger boxes and everything are nice and polished. Have all the scripts/prefabs organized in folders.

Feels good, like cleaning the house.


Only single thing that is missing is I need to make a sprite for the jumpable button prefab and have it sprite change when you jump on it to a depressed button sprite. For testing this stuff I just put it on an apple sprite as my switch so you jump on the apple lol. Will make a button sprite or find a free asset 2d button soon and then these things are done. My belt sprite and animation is pretty crappy but it does the job and animates showing the direction. Will probably draw a better one during visual art polish stage.

At this point I think the next step will just be designing out the rest of the game with placeholders and then once that's done -> creating art/music for all the placeholders -> polishing things up.

But yeah I'll probably take a day off working on it tomorrow for some refresh and this is a good spot with everything organized and stage 1 to leave off. Will come back on Saturday and spend all weekend trying to make the rest of the game with placeholders.


Oh and for final questions at this point, this is what I've got:

1. I'm being real good at keeping everything private and [SerializeField], but the methods I'm calling in other scripts I'm using public void method(). Is there a better way I should be doing this to keep them private and not introduce bugs?

2. One of the things I haven't tried to do yet since I haven't needed it is write a script of something that keeps track of stuff between stages/deaths. Like your score and lives if you use lives (this game isn't going to use lives so it's just restart scene on death, I like platformers these days with no life counters and just a lot of checkpoints).

Does doing this have something to do with don'tdestroyonload? Because I googled that to stop the stage BGM from starting over on death and I use that and it basically keeps a separate instance going with the music in it that is separate from the scene.

Or do you put all that in the gamemanager and just have the gamemanager not be destroyed on load so it can carry over these things? I feel like this will be helpful to learn for creating inventory systems that carry between scenes/stages. I.e. I want to know if my character picked up a Jetpack in the previous stage and should now be flying around.
« Last Edit: April 22, 2022, 03:36:41 AM by Bebpo »

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #309 on: April 22, 2022, 07:07:19 AM »
I'm making AN ENTIRE ROOM OF NOTHING BUT CONVEYOR BELT PLATFORMING in order to justify all this time spent on this logic problem.

 :lol

I'm pretty sure this is the background info on Sonic 1s Marble Zone too

Quick question,

If I want switches and stuff to only activate when colliding with feet, do I basically make a gameobject and attach it to the player called "feet" with a feet box collider and then tag it feet and use that with these objects like standing on buttons? (and put their collision boxes off the ground a bit so running into it won't trigger with ground feet)

So you're probably familiar with the idea of the 'hitbox', let me introduce you to its evil twin the 'hurtbox' - this is usually used in things like fighting games to resolve things like hit priority, but you can also use it to do shit like marios 'jump on head' kills, or touching things only with your feet by jumping on them rather than running into them;



Oh and for final questions at this point, this is what I've got:

1. I'm being real good at keeping everything private and [SerializeField], but the methods I'm calling in other scripts I'm using public void method(). Is there a better way I should be doing this to keep them private and not introduce bugs?

Nah, the 'correct' way of doing OOP coding includes encapsulation, so you have a different script 'responsible' for every aspect, but never directly modified by other scripts; ie, if you have a 'health' class, you can access that class to get / set health values from enemy objects, player objects, destructible scenery objects, boss objects, etc but there's only one class that actually determines how health is handled, so if you need to refactor anything theres only one bit of code you need to change, and anything that accesses health via public methods are all still good (in theory).

Like... don't sweat to what extent you're adhering to the 'correct principles' of OOP while you're still just figuring out what shit works, but having private variables and public methods is pretty robust and secure whether thats for enterprise or game dev.

2. One of the things I haven't tried to do yet since I haven't needed it is write a script of something that keeps track of stuff between stages/deaths. Like your score and lives if you use lives (this game isn't going to use lives so it's just restart scene on death, I like platformers these days with no life counters and just a lot of checkpoints).

Does doing this have something to do with don'tdestroyonload? Because I googled that to stop the stage BGM from starting over on death and I use that and it basically keeps a separate instance going with the music in it that is separate from the scene.

Or do you put all that in the gamemanager and just have the gamemanager not be destroyed on load so it can carry over these things? I feel like this will be helpful to learn for creating inventory systems that carry between scenes/stages. I.e. I want to know if my character picked up a Jetpack in the previous stage and should now be flying around.

This is whats called a singleton; people will shit talk it online as being over used, but its overused because its super fucking handy.
That object pooling you had in your first project was probably setup as a singleton too.
It's super common for a GameManager to be setup as a static persistent object for obvious reasons - you're only gonna be running one version of the game at a time, right? - but you can also have singleton classes for stuff like audio playback (for exactly the same reason you already implemented that) or UI stuff, or data management.
Basically, anything that you want to apply across level loads and there will definitely only be one version of is a good candidate for being a singleton.

Uncle

  • Have You Ever
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #310 on: April 22, 2022, 07:45:15 AM »
I'm making AN ENTIRE ROOM OF NOTHING BUT CONVEYOR BELT PLATFORMING in order to justify all this time spent on this logic problem.

 :lol

I'm pretty sure this is the background info on Sonic 1s Marble Zone too

also this



"These goddamn gun cameras were a nightmare to debug and you're telling me we only have a half a dozen in the entire game?  Fuck it, I'm adding an extra room."
Uncle

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #311 on: April 22, 2022, 02:37:53 PM »
Damn, I killed a HDD backing up my Unity folder lol


Like this computer I built was built a couple years pre-pandemic so probably about 4 years old now and I brought over a few old SATA drives from my old rig so I have like 4 hard drives on this thing. 1 is totally unused, 1 is backup, 1 is for storage, 1 is main SSD for installed stuff.

I tried copying the unity folder over to the backup one and started hearing some clicking and went to bed. Woke up and it was still clicking non-stop so I reset the computer which crashed and then started it up and...drive is gone lol

Thankfully I don't think anything important was on it as it was just a backup/mirror of my storage drive really in case that ever died. And I still got one totally unused drive so I'll just try backing up my storage drive again to this one instead tonight.

But yeah the Unity folder was like 60,000 files already. Was too intense for my old HDD  :lol

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #312 on: April 22, 2022, 02:47:44 PM »
Actually, just looked and my storage drive is a 4TB with 2.5TB used and my remaining empty HDD is only 900GB free. Will need to swap drives if I wanna backup everything again (alternatively probably would just make sense to pick up another 4TB drive and have them mirror each other).

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #313 on: April 23, 2022, 03:00:13 AM »
Been looking into statics.

For my audiomanager which I want so the music keeps its spot on scene reset on death, for changing BGMs per level/area/scene, would it make the most sense to have my audiomanager gameobject basically loaded with the entire game soundtrack and all the tracks and then I could put a public method on it called "ChangeTrack(track name)"

And then in any other script I can just tell it to ChangeTrack(put track name here) and then it will switch currentBGM private variable in the static to whatever track name is and play it?

I'm not sure where I would put code to call this, maybe a script on an object called [Scene_X_Start_Object] which has a script for that one scene and calls on start to change track and set whatever else for the scene? 

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #314 on: April 23, 2022, 04:19:54 AM »
I know I have the Dialogue System to try out, but at night sometimes I've just been finding myself watching random youtube videos on doing game things in Unity lately. Just a curiosity thing now that I'm getting the hang of all this and it's neat seeing all the ways real world game effects/systems/interactions are made in Unity.

I thought this video part 1 of 2 was cool in how they basically took Undertale and then showed you how to create a dialogue system that is close to it. The letter by letter (array of characters displayed one at a time) with goofy sounds for each letter and a background & portrait of the character talking is pretty classic and flexible, so if for some reason I can't use the dialogue system I bought I may try this:

« Last Edit: April 23, 2022, 04:24:47 AM by Bebpo »

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #315 on: April 23, 2022, 07:54:07 AM »
But yeah the Unity folder was like 60,000 files already. Was too intense for my old HDD  :lol

Yeah, actually that's another gripe I have with Unity, it literally creates a unique-per-machine 'shadow file' of every fucking file in a project, and also metadata files for every asset file in a project, so you end up with literally thousands of fucking files in a near empty project.
Like, if you're using Github with unity stuff, theres a whole unity specific gitignore template you really really really should use, to stop all the fucking junk files unity generates bloating your repo.

Its almost worth not actually backing up your unity projects as you think you should (ie as entire folder structures), but by exporting your whole project out as a custom asset .unitypackage and backing that up to import into a 'clean' unity project if you ever want to go back to it.

Been looking into statics.

For my audiomanager which I want so the music keeps its spot on scene reset on death, for changing BGMs per level/area/scene, would it make the most sense to have my audiomanager gameobject basically loaded with the entire game soundtrack and all the tracks and then I could put a public method on it called "ChangeTrack(track name)"

And then in any other script I can just tell it to ChangeTrack(put track name here) and then it will switch currentBGM private variable in the static to whatever track name is and play it?

I'm not sure where I would put code to call this, maybe a script on an object called [Scene_X_Start_Object] which has a script for that one scene and calls on start to change track and set whatever else for the scene? 

I'm happy to post mu singleton script if you want it, like I say, they're so fucking useful everyone uses them for something.

In usage terms, just create an empty gameobject in your initially loaded scene (and call it _audiomanager or whatever) and put it at the top of your hierarchy.
You can also have an "_Managers" empty, with children for _GameManager, _AudioManager, _LevelsManager, _ProfileManager, _AchievementsManager etc each with their own singletons controlling that stuff too.

You're right, you absolutely can use it as a 'jukebox'; you can also use it as a master mixer, so if you have any game settings for audio volume you can store them there and route all SFX through it to ensure they're obeyed everywhere (and can do seperate SFX / Music volume controls).

You can also use it to crossfade between tracks (like, if you have a 'general gameplay' track, but also a more uptempo 'times running out' or 'shits going down' track) from contextual calls (like timer less than 1 minute, or unit manager is spawning in boss or whatever).

You can also do a fairly easy ghetto custom soundtracks thing, by making a folder called uhhhhh streamable assets I think it is, and then explicitly pointing to that in your manager and creating an array of any music it finds in there, and players will be able to drag and drop their own MP3s into that folder, and it will scan them all and add them to a playlist.

The letter by letter (array of characters displayed one at a time) with goofy sounds for each letter and a background & portrait of the character talking is pretty classic and flexible, so if for some reason I can't use the dialogue system I bought I may try this:

I'd be willing to bet IRL money the system you bought has a 'typewriter' text effect built in, probably also with an audioclip for the audio effect; hell, I'd suspect it probably has a randomised variance audioclip so you can do animal crossing / banjo kazooie style nonsense sounds that match text

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #316 on: April 23, 2022, 01:12:16 PM »
Oh! Yeah exporting a package for backup makes a ton of sense. Will do that instead from now on. Hopefully kill less HDDs that way.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #317 on: April 23, 2022, 09:26:56 PM »
Sometimes I just want to throw everything in the fire. I'm having the worst luck on this games on the weekends when I actually have time to spend on it. Instead of making tons of progress and getting lots of rooms and areas done or art/music or whatever I get hung up on something, end up fucking around in scripts and googling and watching tutorials for 3-5 hours and end up fucking up my existing scripts because I'm trying to mod them to get something to work and then I have to spend hours just fixing my scripts to get things back to how they were. It's depressing when I get so little done and I lose my weekends.


For the last 3 hours I've wasted my entire Saturday afternoon just trying to make a goddamn working fucking checkpoint. Which I already had as a prefab in the class version but it was so entwined with their game manager I figured I'd just write one from scratch here.


First I was like "oh shit, the way this game is setup is using loadscene on death so I can't just save the checkpoint position and respawn there because it'll destroy the checkpoint position", so this is a good time to try to practice and create a singleton/game manager where one of the several variables I can carry over across scenes will be current checkpoint location.

-> Cue 90 mins of trying to make a 10 line static instance with a single Vector 2 position variable work and failing every time and realizing I have no fucking idea what I'm doing and every example of a singleton/game manager is complicated and doing lots of shit and for a start I just want it to hold ONE goddamn variable.

So then I give up and decide ok I'm going to do it this way:

1) If you have a checkpoint it gets registered in the currentCheckTracker and then upon death the scene doesn't reload, you just move transform position to the checkpoint after the death animation plays -> trigger in animation to respawn_at_checkpoint.

2) If you haven't gotten a single checkpoint registered yet, you just do the normal reload scene on death.

In theory this actually works better because if the player collects some pick up items, hits a checkpoint and dies and respawns at the checkpoint, those old pick up items shouldn't respawn. Then again now you can pick up collectibles, die and respawn at checkpoint with those collectibles picked up so you can do suicide runs which isn't great.


Anyhow then I just spent 90 mins on that 1/2 solution and it's not working either because the death animation is all fucked up. The way the tutorial I learned from did death was you do an animation which plays the death animation on death trigger being sent to the animator and then turns off the spriterenderer and then performs trigger restart scene.

So I ditched the spriterenderer turn-off and tried turning the death trigger into a death bool that gets switched to true, plays the death animation and then gets switched to false and you teleport to the respawn checkpoint spot.

But instead I'm getting weird stuff like the animation getting stuck on frame 1 and freezing movement in place. Even if I don't have a checkpoint the animation should play and then trigger reload scene but the character is getting stuck and the scene isn't reloading.

So now my death cycle which was already working is broken and I need to try to fix it and then still try to figure out a way to checkpoint :( And then I can actually make more game. I hate this shit.


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #318 on: April 23, 2022, 09:58:59 PM »
Ok, finally got it working by resetting the death trigger and creating an animation state transition from death to idle called respawn and trigger that.

So now I have checkpoints. Though still have the issue of it doesn't reset the collectibles grabbed since the last checkpoint but Idk how to do that.


I GUESS you could make copies of the level and every checkpoint would async smoothly load the next scene and death would restart the current scene so you'd keep restarting from the latest checkpoint with all the stuff ahead of you reset. But this would also respawn the stuff behind you and you'd have to keep track of which items you picked up already to destroy upon loading the new scene. /sigh, just so much work.

Will leave as is and people can suicide run if they want to get the collectibles.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #319 on: April 23, 2022, 10:19:44 PM »
Ok, checkpoints still not working. I'm gonna lose the entire day just trying to get checkpoints which were already working in the build I threw out to work here, but I need working checkpoints :(((((((((((((((

Code: [Select]
public class CurrentCheckPointTrack : MonoBehaviour
{
    // Start is called before the first frame update

    [SerializeField] private Checkpoint chk = null;

    public void Start()
    {
        chk = null;
    }
    public void AddCheckpoint(Checkpoint talky)
    {
        chk = talky;
        Debug.Log("new checkpoint spot = " + chk.transform.position.x + chk.transform.position.y);
    }

    public Vector2 GetCheckpoint()
    {
        if (chk != null)
        {   
            return new Vector2(chk.transform.position.x, chk.transform.position.y);
        }
        else
        {
            Debug.Log("No Checkpointset");
            return new Vector2(0, 0);
        }
    }
       
}

So this is nonsense.

If I'm looking at the checkpoint tracker it has a serialized field showing the current checkpoint that you will respawn at. When I pass a new checkpoint the debug log tells me the checkpoint variable chk now equals the position of checkpoint #2

BUT the serializedfield for that same fucking variable chk still says checkpoint #1 and when I die, viola! I respawn at checkpoint #1 even though the debug log is telling me the coordinates for the variable is at checkpoint #2.

What the hell is going on?

I wonder if this might have something to do with prefabs and checkpoint #1 being a prefab but 2+ not being because they are copies or something.
« Last Edit: April 23, 2022, 10:31:03 PM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #320 on: April 23, 2022, 10:36:44 PM »
Maybe I'm overcomplicating this checkpoint setup. I have my tracker keep a private variable of the current checkpoint and new checkpoints add themselves as the current checkpoint and when you die it runs getcheckpoint() from the tracker and gets the checkpoint coordinates and respawns at those coordinates.

I'm looking at how my class template does it and it's way less code. This is my class version:

Tracker
Code: [Select]
public static class CheckpointTracker
{
    // The most recently activated checkpoint
    public static Checkpoint currentCheckpoint = null;
}

That's it.

Checkpoint
Code: [Select]
public class Checkpoint : MonoBehaviour
{

    public Transform respawnLocation;
   public GameObject checkpointActivationEffect;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            if (CheckpointTracker.currentCheckpoint != this && checkpointActivationEffect != null)
            {
                Instantiate(checkpointActivationEffect, transform.position, Quaternion.identity, null);
            }

            // Set current checkpoint to this and set up its animation
            CheckpointTracker.currentCheckpoint = this;
        }
    }
}

So it just checks the static to point to this checkpoint and does a checkpoint activation effect. Then the player respawn gets that position from the static.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #321 on: April 23, 2022, 11:04:13 PM »
Ok, I just used theirs and it worked. What a waste of time. I guess I just was getting static stuff wrong initially because I'd never used it before and because instead of just using one basic static variable I jump straight to trying to make a static gamemanager script I could assign multiple things to and when I failed at that I tried a non-static route.

Also in the inspector my [Serializefield] for the currentcheckpoint variable still doesn't actually update in the inspector when I'm using the editor and hit a new checkpoint, but I have a debug log shout out the new spot coordinates and then I test dying and it seems to work fine.

Next challenge will be figuring out how to keep the score across stages because I'm doing things in the latter stages based off total score (i.e. multiple ending branches).

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #322 on: April 24, 2022, 12:07:11 AM »
Next thing I'm wasting an hour of my life on.

I have a cool little script called "flip sprite" where if you run past a NPC they turn and follow your direction. This works based on collision/triggers as you pass through them.

But if you run past them so they turn from looking left to looking right, but then you die and you respawn at a checkpoint to the left of them they are still looking to the right when you are on the left.

I thought this would be a 5 min fix of just getting players transform position at the start, assigning it to a variable and just having on update for these flippy sprites an if statement looking to see if the player's transform.position.x is > or < then the transform.position of the sprite and to flip accordingly.

But it's not working at all. I don't even know why. Why does nothing simple ever work right. This isn't worth spending hours on :\

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #323 on: April 24, 2022, 12:15:56 AM »
Ok, fixed it by instead of putting a drag & drop serialized field with the player in it I tried just FINDING the player and it works now. Who the fuck knows why, but I'll take it

I just switched the serializedfield game object player1 and then p1p grabbined from the serializedfield gameobject player1.getcomponent<transform>(); to

p1p = GameObject.FindWithTag("Player").transform;


Maybe it's because I was called getcomponent transform in the first case and the second I'm just assigning the transform? Is the basic transform of an object not a component of that object?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #324 on: April 24, 2022, 01:35:10 AM »
So I got a few more things taken care of. I think in terms of understanding coding and being able to put my own game together from start to finish with all the whirly gags I like, I just need one more core concept.

I need a top level scene script where I can mess with objects in the scene. Like if I want to turn on a UI element once a counter reaches a certain # or set a pause canvas active if you hit escape.

I'm assuming this is basically the game manager to control the scene + the ability to carry over variables between scenes like score/lives/etc...

I'm trying to find a good youtube video on making a game manager script but haven't found the right one yet. I think when I understand this and how to do static stuff better I'll have everything I need.

This project has been very difficult. My first project I relied too much on the core class template and was more like a total conversion mod of it. Plus by dividing every event into its own scene and not having much/any player interaction because it was a shmup I could just use timers for events and loading scenes. Whereas this is learning how to make a game from start to finish from scratch and interacting constantly with stuff.

At least when I get to my next project I think maybe it'll be a bit easier from that point? Since I'll have all these basics down. Fingers crossed.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #325 on: April 24, 2022, 02:23:49 AM »
Also regarding statics and stuff I don't really understand, now that I have a pause menu and can go back to the main menu, how do I tell this static to go away.

Code: [Select]
public class Keep_Music_On_Death : MonoBehaviour
{

    static Keep_Music_On_Death instance = null;

    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            GameObject.DontDestroyOnLoad(gameObject);
        }
    }
}

Basically 1 BGM starts in Stage 1 but when you quit to the main menu it keeps playing, same with stage 2. This is pretty bad if I want different music for different scenes which I do.

The only reason I'm even using this thing is so that the music doesn't reload on scene-reload when you die. But I'm held hostage with it because I don't know how to use it since it destroys itself in other scenes.

Tbh now that I have checkpoints I could just put a checkpoint at the player start and then never have to reload the scene during a stage and I can just do music like normal like I did last game with each scene having a level_music gameobject with a source BGM.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #326 on: April 24, 2022, 02:52:12 AM »
Ok, did some testing without watching/reading tutorials on static and just trial & error-ing. My goal right now is just to have the score carry from stage 1 -> 2 in the scoredisplay.

I sorta did that but I have a few errors. Here is my test code:

Code: [Select]
public class TacosTesting : MonoBehaviour
{
    static TacosTesting instance = null;
    public static int numbertest = 0;

    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            GameObject.DontDestroyOnLoad(gameObject);
        }
    }

    public int ReturnNumber()
    {
        return numbertest;
    }
}


-Now when I try to increase numbertest from another script++, it works
-When I try to send numbertest to the scoredisplay UI text to show the score count, it works
-When I try to call new INT Burrito = TacosTest.ReturnNumber(); it doesn't work. So I don't know how to do methods in a static script from another script.


Also a side thing I've had this whole time is my game kind of hiccups when loading level 2 from level 1's end goal. The tutorial I read had me using Invoke on the sceneload to give 1 second for the level clear sound effect to play, it does and when I load my character is in some weird jump animation and my controls are horizontally locked on the x-axis and sometimes when I jump forward right away it auto resets me to the start of the stage.

I'm pretty sure the jumpyness is all caused by the don't destroyonload stuff.

It's so weird, but I may get around that by putting in a player thing that says at new scene load to go static for 1 second before being able to move. Game just seems to be hiccuping on physics/controls for the first second in a new stage.


« Last Edit: April 24, 2022, 03:19:18 AM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #327 on: April 24, 2022, 03:44:21 AM »
Well I've added the ability to hit "esc" or back button if you're not in the main menu screen or ending screen and to load up the pause menu to this TacosTest static script.

Seems to work well. So I got my scene controller and score variable carry-ing gameobject.

I guess I'm slowly turning this tacostest into a game manager?

Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class TacosTesting : MonoBehaviour
{
    static TacosTesting instance = null;
    public static int numbertest = 0;
    public GameObject PauseScreen;

    void Awake()
    {
     

        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            GameObject.DontDestroyOnLoad(gameObject);
        }
    }

    private void Update()
    {
        if (SceneManager.GetActiveScene().buildIndex == 0)
        { numbertest = 0; }
        if (SceneManager.GetActiveScene().buildIndex == 0)
        { Time.timeScale = 1;  PauseScreen.SetActive(false); }

        if (SceneManager.GetActiveScene().buildIndex != 0 && SceneManager.GetActiveScene().buildIndex != 3 && Input.GetButton("Cancel"))
        { Time.timeScale = 0;  PauseScreen.SetActive(true); }
    }

    public int ReturnNumber()
    {
        return numbertest;
    }
}

At this point I have most of the code stuff I wanted to do what i wanted implemented so tomorrow hopefully can focus on designing new stages. Today was just all tools stuff.

Actually simplified this even further by taking the BGM don't destroy on load code and putting it in the tacostest manager (and having one less script/gameobject), taking the pause screen and putting it as a child under the tacostest manager (so I don't need to put a don'tdestroy on it) and did the same with my screenshot app.

Now it looks pretty clean where only a single gameobject (tacostest) is carried over between stages and it has everything nested in it. Definitely feeling like I may rename this to gamemanager by the end of tomorrow as I give it more and more abilities.
« Last Edit: April 24, 2022, 03:59:30 AM by Bebpo »

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #328 on: April 24, 2022, 08:20:46 AM »
Ok, fixed it by instead of putting a drag & drop serialized field with the player in it I tried just FINDING the player and it works now. Who the fuck knows why, but I'll take it

I just switched the serializedfield game object player1 and then p1p grabbined from the serializedfield gameobject player1.getcomponent<transform>(); to

p1p = GameObject.FindWithTag("Player").transform;

I'm gonna guess your respawn code is like the 'teleporter' from The Prestige, and you're not actually moving the current player somewhere, you're destroying them and then creating a new copy somewhere else?

Because that'll be why your cached reference doesn't work as a pointer anymore - its actually a completely different hugh jackman.

Findwithtag is actually a kinda terrible way to get pointers, but if it works it works - either using your original pointer reference and disabling it, moving it, reenabling it or grabbing the pointer reference at reinstantition would be better ways of doing this, but - no shade - you're at the point where you're learning to get shit working, so imo don't sweat the 'proper ways' until youre comfortable with ways that work.

Also regarding statics and stuff I don't really understand, now that I have a pause menu and can go back to the main menu, how do I tell this static to go away.

It seems like you're leaning more into singleton use, but yeah, the point is it never goes away, you want to handle whatever it exists for on it.
So if you want a different track per level, you're better off having an audiomanager singleton that has ALL the music on it, and then loads up the next tune when the next levels loaded, rather than having an individual music track object per level (or at worst, if you do have a single object for music per level, they are triggered by your singleton rather than acting independtly of each other).

Doing it this way lets you do cool stuff like cross fade from one track to another while the levels loading and shit.

-When I try to call new INT Burrito = TacosTest.ReturnNumber(); it doesn't work. So I don't know how to do methods in a static script from another script.


So the important bit of your code here that I think you're overlooking is this bit;

Code: [Select]
    static TacosTesting instance = null;
Tacostesting is your class name, the thing that actually holds that code and the variables is a variable of <T> (type) TacosTesting named instance.

So you need to find that - luckily as its static, it should be as easy as
TacosTest.instance.ReturnNumber();

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #329 on: April 24, 2022, 01:14:31 PM »
Ok, fixed it by instead of putting a drag & drop serialized field with the player in it I tried just FINDING the player and it works now. Who the fuck knows why, but I'll take it

I just switched the serializedfield game object player1 and then p1p grabbined from the serializedfield gameobject player1.getcomponent<transform>(); to

p1p = GameObject.FindWithTag("Player").transform;

I'm gonna guess your respawn code is like the 'teleporter' from The Prestige, and you're not actually moving the current player somewhere, you're destroying them and then creating a new copy somewhere else?

Because that'll be why your cached reference doesn't work as a pointer anymore - its actually a completely different hugh jackman.

Findwithtag is actually a kinda terrible way to get pointers, but if it works it works - either using your original pointer reference and disabling it, moving it, reenabling it or grabbing the pointer reference at reinstantition would be better ways of doing this, but - no shade - you're at the point where you're learning to get shit working, so imo don't sweat the 'proper ways' until youre comfortable with ways that work.

Also regarding statics and stuff I don't really understand, now that I have a pause menu and can go back to the main menu, how do I tell this static to go away.

It seems like you're leaning more into singleton use, but yeah, the point is it never goes away, you want to handle whatever it exists for on it.
So if you want a different track per level, you're better off having an audiomanager singleton that has ALL the music on it, and then loads up the next tune when the next levels loaded, rather than having an individual music track object per level (or at worst, if you do have a single object for music per level, they are triggered by your singleton rather than acting independtly of each other).

Doing it this way lets you do cool stuff like cross fade from one track to another while the levels loading and shit.

-When I try to call new INT Burrito = TacosTest.ReturnNumber(); it doesn't work. So I don't know how to do methods in a static script from another script.


So the important bit of your code here that I think you're overlooking is this bit;

Code: [Select]
    static TacosTesting instance = null;
Tacostesting is your class name, the thing that actually holds that code and the variables is a variable of <T> (type) TacosTesting named instance.

So you need to find that - luckily as its static, it should be as easy as
TacosTest.instance.ReturnNumber();

Nah, my respawn code was just moving the transform position. I'm still using the same code and it works now with the static variable for currentcheckpoint.

I'm not sure why my checkpoint tracker was messed. I also get why find with tag is bad, but there's only going to be one object per scene tagged player (in an SP game) so I think it should be ok here.

Thanks on that singleton bit, I feel like it's way safer to have a private method on that to addtestnumber() and retrievetestnumber() with a private int than having a generic static testnumber int that could easily get messed up. If I can call methods in this I'll switch it to that.

Oh, and for Singletons, can't I just tell it to destroy itself if certain things happen? Like if scene = 3 destory.
« Last Edit: April 24, 2022, 01:19:40 PM by Bebpo »

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #330 on: April 24, 2022, 03:44:26 PM »
So first thing I'm trying this morning is removing

Code: [Select]
public static int numbertest
in my singleton tacostesting class

and replacing it with:

Code: [Select]

private int numbertest;

 public void UpdateScore()
    {
        numbertest++;
    }

    public int GetScore()
    {
        return instance.numbertest;
    }

Cool this worked, though I had to change the static variable at the top of the class from static instance TacosTesting = null; to public static instance TacosTesting = null for other scripts to be able to call methods in it.

But now that I can do this I think I can do a lot of stuff I want.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #331 on: April 24, 2022, 05:23:41 PM »
Having a weird bug where I can't use teleports with my movement code.

Like my respawn on death works fine. And that just teleports player.transform.position to currentcheckpoint and switches back to idle animation and static body on death back to dynamic.

But teleport the code is literally just this

Code: [Select]
public class Teleporter : MonoBehaviour
{
    public GameObject teleportPoint;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (teleportPoint != null)
        {
            collision.gameObject.transform.position = teleportPoint.transform.position;
        }
    }

}

And I throw in a blank gameobject somewhere as the exit point.

And it works and I teleport to the new spot,

but it completely fucks up the player?? the first frame I appear in the new spot is OK, but the second I hit left or right, the player gets locked into the running animation even if I'm idle and even worse the player can't jump anymore.

But doing this same thing on respawn works perfectly fine...

No idea what is causing it, I could change the player's RB to static when teleporting and back to Dynamic after exiting which might fix it but that removes any ability to take motion through teleports so it's not really preferred.

This is the basic movement animation state code on the player. Not sure how teleporting the transform with the teleport code above would mess this up?

Code: [Select]
private void UpdateAnimationState()
    {
        MovementState state;

        if (dirX > 0f)
        {
            state = MovementState.running;
            sprite.flipX = false;
        }
        else if (dirX < 0)
        {
            state = MovementState.running;
            sprite.flipX = true;
        }
        else
        {
            state = MovementState.idle; ;
        }

        if (rb.velocity.y > .1f)
        {
            state = MovementState.jumping;
        }
        else if (rb.velocity.y < -.1f)
        {
            state = MovementState.falling;
        }

        anim.SetInteger("State", (int)state);
    }

Alternatively I may just make separate scenes for teleport triggers (I'm talking about entering doors) instead of teleporting you to different stages within the same level at different spots.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #332 on: April 24, 2022, 05:28:13 PM »
Well, turning the Rigidbody static while teleporting and back to dynamic fixed it. So something was messing up the physics during the teleport idk why

Code: [Select]
public class Teleporter : MonoBehaviour
{
    public GameObject teleportPoint;
    private Rigidbody2D rb;

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (teleportPoint != null)
        {
            rb = collision.GetComponent<Rigidbody2D>();

            rb.bodyType = RigidbodyType2D.Static;
            collision.gameObject.transform.position = teleportPoint.transform.position;
            rb.bodyType = RigidbodyType2D.Dynamic;
        }
    }

}

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #333 on: April 24, 2022, 05:40:53 PM »
So I figured it out I think, because I'm getting editor errors that the teleport code is trying to get a rigidbody2d component off the wall check object within player and feet object within player.

I think when it was teleporting it maybe only was teleporting the player and not their body part children?? Since the feet do the ground check if the feet didn't come with the player that would explain not being able to jump.

But on dying & respawn it doesn't have this issue? Maybe turning the whole player static and back to dynamic resets this? But then I'm doing that here with the teleporter and it's giving me errors and I don't get those errors when respawning after death.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #334 on: April 24, 2022, 05:47:44 PM »
Ok, figured it out. Because I had an if/else since I wanted else to cover things like crates going through a teleporter

It was doing 3 collisions on trigger, player object, wallcheck object, feet object.

And would teleport all 3 to the same transform.position which...means the feet would be moved to the center of the player and same with the wall check and the player's body would be all fucked up.


So the solution was to get rid of the else statement and just do "if compareTag("Player") and then do an elseif CompareTag ("Crate") for anything else I want to throw through a teleport.

Also now I can get rid of all that rigidbody changing while teleporting since it wasn't the issue.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #335 on: April 24, 2022, 06:30:39 PM »
I'm trying to add multiple conveyor belts to my reverse switch so a single switch stomp reverses a bunch of belts instead of just one. First time trying to use arrays and not sure why this isn't working? It says null error that the method calls are "object reference not set to an instance of an object"

and stomping on the switch does nothing

Code: [Select]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Basic switch can jump on if you put a trigger on top
/// If trigger hits feet, switch is switched
/// This trigger flips direction of receiving object (belt in this case) if it has a flip direction method
/// </summary>
public class ReverseSwitch : MonoBehaviour
{
    [SerializeField] private GameObject[] Belt;
    private BasicConScript[] BeltScript;
    private int currentIndex = 0;


    private void Start()
    {
        if (Belt != null)
        {
            while (currentIndex < Belt.Length)
            {
                BeltScript[currentIndex] = Belt[currentIndex].GetComponent<BasicConScript>();
                currentIndex++;
            }
            currentIndex = 0;
        }
    }


    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Feet"))
        {
            while (currentIndex < Belt.Length)
            {
            BeltScript[currentIndex].FlipDirection();
                currentIndex++;
            }
        }
    }

}

And here's how it looks in inspector





logically it seems like it should work?

Belt length = 2
starts at 0

gets component for Belt 0 and puts it in scriptholding object for script0
increases index+1
same for 1 and 1
increases index+1
now index = 2 and the while statement ends.

index reset back to 0

then on jumping on the switch, index is 0,

for each 1/2 it runs the flip() on both their scripts
index+1 each time
then index = 2 and while statement ends and collision trigger is done?

What am I missing?


Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #336 on: April 24, 2022, 11:48:57 PM »
Making games is a lot of work  :doge

Got a couple more stages done with placeholder assets today. Outside not figuring out arrays (so for now I just stuck 2 button gameobjects on top of each other so you hit both triggers on jumping on the button), everything else worked.

Still have a fuckload to go just to finish the whole game with placeholders before moving into the art phase. At least I'm being good about fixing 98% of issues and bugs now instead of leaving it all to deal with at the end.

Also just opened my PC up and installed the new HDD and am creating it as a mirror now for my storage drive. The case is not designed well for HDD access, but luckily the first accessible drive I pulled was the dead drive.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #337 on: April 25, 2022, 01:57:45 PM »
I'm trying to add multiple conveyor belts to my reverse switch so a single switch stomp reverses a bunch of belts instead of just one. First time trying to use arrays and not sure why this isn't working? It says null error that the method calls are "object reference not set to an instance of an object"

What am I missing?

I dunno man, I'm afraid I can't debug this for ya from this info.

what I would say though is it seems a little overcomplicated; couldn't you do something like:

Code: [Select]
for (int i = 0; i < BeltScript.length; i++)
{
     BeltScript[i].FlipDirection();
}

instead?

Making games is a lot of work  :doge

IKR? :lol

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #338 on: April 25, 2022, 04:16:08 PM »
Wait, do I not need to call getcomponent<>(); on a gameobject to get its script when calling a method within a script on it?

I thought I had to get the script as a variable and call the method from that variable.


Your method sounds good, I'll give that a try next time.



GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #339 on: April 25, 2022, 04:24:28 PM »
Wait, do I not need to call getcomponent<>(); on a gameobject to get its script when calling a method within a script on it?

I thought I had to get the script as a variable and call the method from that variable.

if your array was of Type Gameobject, you might have to, but its of Type BasicConScript (which is the class I assume contains that method) so you can pretty much assume an array of component<BasicConScript> definitely has component<BasicConScript>

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #340 on: April 25, 2022, 06:16:34 PM »
Making games is a lot of work  :doge

:P

So worth it tho :lawd

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #341 on: April 25, 2022, 06:29:24 PM »
Wait, do I not need to call getcomponent<>(); on a gameobject to get its script when calling a method within a script on it?

I thought I had to get the script as a variable and call the method from that variable.

if your array was of Type Gameobject, you might have to, but its of Type BasicConScript (which is the class I assume contains that method) so you can pretty much assume an array of component<BasicConScript> definitely has component<BasicConScript>

I think there might be a typo in there, but I'll mess around with your code tonight and figure it out.

I've just never used arrays/enums before this and I haven't used a list in 22 years. Enums I figured out pretty quick after a few examples used them. Arrays I get in principal but I just need to find the magic words to make them work right and lists are pretty similar but last time I wrote a script with a list was when I was in college so I need to actually try to do those again.

Just haven't run into any real use for lists or even strings outside tags in my projects yet.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #342 on: April 25, 2022, 06:34:11 PM »
Making games is a lot of work  :doge

:P

So worth it tho :lawd

Yeah, I get excited thinking about game design stuff.

This morning in bed I came up with the scenario design for my 3rd game. I really like it and it's a pretty complete scenario. So now I have games #1-3 scenario-planned.

And for game #4 I have the gameplay concept and story/scenario is not important in this one so I can figure it out at the time.

Games #1-3 are planned as existential horror trilogy, whereas Game #4 is a colorful Katamari-like fun game that if it turns out alright I would probably try to make an IOS/Android build (in addition to PC/Mac) because it'd fit in with that audience.

I think my year 1 goal, which would go through March 2023 since I started at the beginning of March 2022, is to get those 4 games done, which includes fully remaking & expanding the first game. If Games 1-3 turn out ok, might try to package them as a single 3-games-in-1 thing.

If I can pull that off, in year 2 I'll start thinking about games #5/#6 which I'm not even gonna think about yet besides that I want to do a point & click adventure game as game #5 and then an rpg as game #6. Haven't decided on both whether they'd be 2d or 3d. Won't make that decision until I get to them.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #343 on: April 25, 2022, 08:48:52 PM »
I'm trying to add multiple conveyor belts to my reverse switch so a single switch stomp reverses a bunch of belts instead of just one. First time trying to use arrays and not sure why this isn't working? It says null error that the method calls are "object reference not set to an instance of an object"

What am I missing?

I dunno man, I'm afraid I can't debug this for ya from this info.

what I would say though is it seems a little overcomplicated; couldn't you do something like:

Code: [Select]
for (int i = 0; i < BeltScript.length; i++)
{
     BeltScript[i].FlipDirection();
}

Ok, tried this and it doesn't work either because it's not set to an object.

I have

GameObject = Belt = the conveyor Belts gameobject
GameScript = BeltScript = on the conveyor Belt GameObject as a script, the FlipDirection() is a method within this script

Now, I am using a

Jumpable switch GameObject = ReverseSwitch = the game object you can jump on
ReverseSwitch Script = ReverseSwitch = The script that tells the switch what to do which is when stomped on to tell the targetObject to run FlipDirection


This works fine with a single Belt where I getcomponent Belt's script, then when button is jumped on switch tells belt's script to run flipdirection.

This does not seem to work at all with arrays because it's not finding the object?


I think I need to just run a dummy practice tutorial on how to right a working array. I'm obviously getting some logic wrong on how you do things with arrays.[/code]

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #344 on: April 25, 2022, 08:56:39 PM »
Ah, I think my issue with arrays is I don't know the correct way to add to an array in runtime.

I'm pretty sure I do need to GetComponent of each Belt and stick their script in an Array index variable and then I pull the script out of that array and tell the script to run flip each time.

I guess I can circumvent this for now just by making the scriptholders a bunch of present variables like Script 0/1/2/3/4 and put first belt's script into 0, 2nd belt's script into 1, etc... for length of the belt. Should work, will test this now until I learn how to add to an array.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #345 on: April 25, 2022, 09:02:43 PM »
So yeah, this code works fine, using one array-ish.

Code: [Select]
    [SerializeField] private GameObject[] Belt = null;
    private BasicConScript BeltS1;
    private BasicConScript BeltS2;
    private int i = 0;





    private void Start()
    {
            BeltS1 = Belt[i].GetComponent<BasicConScript>();
            i++;
            BeltS2 = Belt[i].GetComponent<BasicConScript>();
            i = 0;


    }


    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Feet"))
        {
            BeltS1.FlipDirection();
            BeltS2.FlipDirection();
        }
    }

But you have to manually adjust the code for however many belts you want to reverse at once each time. What I want to do is basically to take that

BeltS1
BeltS2
...

and turn it into a callable array called

BeltS[]

Google is telling me this is how you add to an array in C#, will try it out

Code: [Select]
private T[] AddElementToArray<T>(T[] array, T element) {
    T[] newArray = new T[array.Length + 1];
    int i;
    for (i = 0; i < array.Length; i++) {
        newArray[i] = array[i];
    }
    newArray[i] = element;
    return newArray;
}

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #346 on: April 25, 2022, 09:13:07 PM »
Bam, got it. Reading that code I saw what I was missing and was causing my error.

I was creating a private array to hold the scripts.
Then I was adding to the array.

Problem is that the array was size 0 initially so it had no room to add to the scripts.
I was missing the one line to create space in the array to slot in the scripts.

     BeltS = new BasicConScript[Belt.Length];

fixed it all. Now I can load up multiple conveyor belts to react to a single switch. This is useful for things in general.

Code: [Select]

public class ReverseSwitchArray : MonoBehaviour
{
    [SerializeField] private GameObject[] Belt = null;
    private BasicConScript[] BeltS;





    private void Start()
    {
        BeltS = new BasicConScript[Belt.Length];

            for (int i = 0; i < Belt.Length; i++)
        {
            BeltS[i] = Belt[i].GetComponent<BasicConScript>();
        }


    }


    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Feet"))
        {
            for (int j = 0; j < Belt.Length; j++)
            {
                BeltS[j].FlipDirection();
            }
        }
    }

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #347 on: April 26, 2022, 12:51:08 PM »
yeah, arrays are fast + cheap, but also kinda brittle.

If you want a list of things that you can add / remove / sort / resize at runtime, you're better off using, well, a List or a Dictionary

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #348 on: April 26, 2022, 01:27:56 PM »
Never heard of a dictionary in coding, will look it up.
Yeah, at some point I should practice making a list. Just like read up an online exercise in C# using lists so I can get the gist of how they work.


So I think the next thing I want to mess with is RNG? Like it seems RNG would be useful for a lot of stuff that you don't have to manually design out. For instance if you have a room shake and debris falling you can set 5 spawn points at the top that drop a debris object and generate an RNG every second between 0-10 and if that number is 1-2 the first spawner goes off, 3-4 the second one, etc...

Like that should work and you have a shaking room that is randomly dropping debris at various spots every second? That way you don't have to like think about the timer design for spawners firing.

Also the conveyor belt array yesterday gave me an idea for a boss fight which includes RNG items being thrown by the boss, so I wanna test that out.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #349 on: April 28, 2022, 04:18:36 AM »
I like that I'm at the point where if I can think up something in my head I can program it to happen.
Like I wanted a boss fight where you can see a bunch of conveyors and bombs drop and you have to adjust the conveyors to move the bombs to hurt the boss and not kill you.

So I made a camera adjusting script triggered by an invisible trigger the size of the boss screen that tells the camera to ignore updates and lock at a specific position zoomed out and adjusted upwards so you can see the vertical stage single screen stage of conveyors. Then I made bombs that kill the player (though right now they just kill on collision and I'd like to polish it with a 3 second beep beep and then kill around a certain damage box that isn't the object's collider). Then I made triggers in the areas that hurt the boss that says when X amount of bomb tag objects are stayintrigger then play boss arm fly up and punch head event and then boss has a script that if damaged x 3 to play death animation and die and spawn exit for boss fight.

I'm still cleaning it out and haven't done the art/sound effects/animations for it yet, but was able to take that concept and write a bunch of scripts and make it work in about 30-60 mins. It's just cool being able to take concepts and create them through scripting and objects.



Basically I took this and am making it happen pretty quick which is cool.

*edit* And then I decide instead of having this at another room on the map that you teleport too, since I want the boss state and bombs to reset on death I change this all to its own scene that reloads on death, which in the process breaks a bunch of the stuff I did and I spend 2 hours fixing it all lolcry
« Last Edit: April 28, 2022, 06:00:07 AM by Bebpo »

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #350 on: April 28, 2022, 02:03:21 PM »
I like that I'm at the point where if I can think up something in my head I can program it to happen.

Yeah, I think thats the interesting stage of coding, where you know 'the lingo' and can look up the manual for the specifics, but get to figure out the approach on handling something

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #351 on: April 28, 2022, 03:49:30 PM »
Yeah, it's fun. I'm still going back and forth on the scope. I keep thinking up ideas for new rooms/areas/bosses, but at the same time I don't think the concept/game is good enough to devote so much time to and the time would be better spent moving on to the next game.

Basically I think my original plan of doing a bunch of short 5-10 min prototypes of different genre and then seeing what works and learning the ropes and then coming back to the ones that work and expanding them into full games...is a good idea.

But somewhere along the way the scope and ideas for this 2nd game started getting to this idea that instead of 10 mins, it could be a full, but very short, indie game with 30 min+ runtime, multiple branches & endings, full controller support, etc...where I'd release it for free on stuff.

I still think that's doable, but just as I'm designing things out with placeholders and thinking about how much time it's going to take to fill in the placeholders as well to keep designing and playtesting out the areas, I'm kind hmmmmm, maybe I want to actually finish this and move on in the next few weeks and not still be working on this game for another 2-3 months before I move on.


It doesn't help that I feel way more confident in my 3rd game. Like I've designed it to be incredibly small in scope since it's my first 3d game and will be a lot of learning the ropes. In terms of assets it's super minimal (like the whole game takes place in 1 room) and I feel like I should be able to churn it out in a few weeks no problem. I also think it's more original and more interesting than this 2nd game I'm working on. So I kind of want to get to it.


My current platformer game is ok so far, like it plays decent and has what I think is a good challenge balance and some good game ideas. But at the end of the day, at least at this point it does not have a single original idea in it, so it's just another platformer with a mix of stuff from all good platformers that came before. I think if I had a good creative gameplay concept I'd be more motivated to stick with this. At this point I'm kind of just building the whole game and then if at some point I go "aha!" and come up with a clever gameplay idea I can edit all the levels/bosses to work with it after.

Originally my plan was like Stage 1->Stage 2 -> Stage 3 with 3 different stage 3's depending on branching
Then Stage 2 became Wiley's Castle from MM and like 6 mini-stages + mid-boss
Then the 6 mini-stages became more like small but actual MM stages with their own bosses

But now I'm thinking of cutting Stage 2 down to like 3 micro-stages + mini-boss + escape from Wiley's Castle sequence -> Stage 3 just being a final boss and calling it a 10-15 min short prototype that like my first game I can come back to later and expand if I want.

Right now I have done w/placeholder assets:

Stage 1
Stage 2 castle with doors
Door 1
Door 2
Door 3
Mini-Boss

Was going to make Door 1/2/3/Mini-boss all a single door stage, but yeah I think for now I'll just have them as separate stuff and basically the entirety of stage 2. Will design an escape sequence and then a transition to stage 3 and then do that + final boss at this point I think.

Ideally by the end of this weekend I'd like the game to be playable from start to finish with placeholder assets, so next week I can spend doing the art/music phase and then the week after polishing it and releasing it.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #352 on: April 28, 2022, 04:04:27 PM »
Oh, is there any easy way to record gameplay and then play it back as a cutscene?

Like if I want when the player steps through a trigger the camera zooms in a bit and the player loses control and the main character walks forward and then the ground breaks apart under them and they fall.

The long way would be to like remove control of the player and then tell the player object in script to like transform.right until this point and play running animation while doing so and then on the spot have the ground play breaking animation -> remove ground and rigidbody physics on the player will make them fall and you can transition to a black screen after a few seconds of falling.

The short way would just be if I could record me walking forward and standing on a spot and then take away the player's control of the MC and then play that bit?

This seems like it would be especially useful for FPS cutscenes where you can just record moving and looking and doing something and then play it as a cutscene at spots.

Google is showing me stuff like this, probably will explain it:




Another question I have for Unity/C#, when do InvokeRepeating, is the time based on something that will be the same across hardware? Or will it be one of those things where at 120fps it'll fire off the invoke method more often than someone playing it at 30fps in the same amount of time? I'm using InvokeRepeating on my spawner to spawn bombs for my conveyor belt boss. Wondering if this is problematic and I should tie it to a time.deltatime thing instead?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #353 on: April 28, 2022, 04:59:46 PM »
So I watched a few videos on making cutscenes in 2d/3d and it makes sense, but I'm not seeing anything that lets you just record gameplay?

Like say you're making an FPS, and you want your cutscene to be the player walks to the wall and jumps twice. Now you can use timeline or whatever and move the player to the wall and make them jump twice,

but there has to be a way to just hit record and the gameplay starts with you in control of the player and you walk over to the wall and jump twice and then hit exit record and now you have your cutscene?

Tasty

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #354 on: April 28, 2022, 05:23:43 PM »
Maybe FRAPs plus a custom camera?

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #355 on: April 28, 2022, 05:27:58 PM »
Seems like Unity Recorder lets you record gameplay but it just makes it a video file, so you can save the video and play it on trigger but that seems stupid to me for in-game stuff idk.

Guess I'll just do it using animator and timeline when I get to it. For my 3d game I do want to do FPS animations where it takes the control away from the player and looks in a certain direction.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #356 on: April 28, 2022, 06:51:30 PM »
Also one of the many lessons I'm learning from this project is for now if I just want to make prototypes all of kinds of genre for practice and then dive in heavy on a bigger project later, that from the start to keep the scope of each of these projects really small.

Game #3 idea I have is good for that.
Game #4 idea all I have is some gameplay loop ideas so can keep it small

Better to be focused initially on a small project you can keep the passion flame going and knock out in a few weeks/month vs losing your way and losing interest.

For example for a 2d platformer, I think a good prototype size idea would've been make a gameplay concept even if it's been done before like "button 2 lets you zero dash once per jump aka move in a direction a few units while invincible", and then just make like 5-10 single room platformer puzzles with a set still camera that increase the complexity using that. Then an ending screen. Maybe throw in a couple of brief couple line dialogue cutscenes every few stages.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #357 on: April 29, 2022, 06:47:54 AM »
Oh, is there any easy way to record gameplay and then play it back as a cutscene?

I mean... this is kind of a bigger topic than you might realise.
If you want to do a traditional 'in engine' style cutscene, you're basically writing non-interactive code to simulate how gameplay actually works (and yeah, you probably want to use Timeline to handle sequence of events, and probably Cinemachine as well to handle precision camera placement / focus / moves) and that's basically going to involve you faking gameplay through animations / placements / translations etc.

Because when you think about it, when you take away the systemic / mechanical aspects of a videogame, you are basically just watching a series of animations.

This is probably the closest to 'hit record and playback' you're likely to get, especially as the unity animator pretty much works like that for any given component, except you're controlling those values through the inspector rather than via input scripts (so if you want to move something 5 units north at 1 unit/second, then rotate 90 left, you can create a new anim, hit record, then make a keyframe at 5 seconds, drag their Z transform to +5, then drag their Y rotation to -90)

If you want to do actual player gameplay repetition (like Super Meatboys Replays, or driving game ghost cars) you're going to want to basically create a class that pretty much records player inputs at timestamps, and then when finished does a stochastic playback of replicating the players gameplay by replicating their inputs (and its going to go wrong if you have non-deterministic gameplay, or randomness involved, and if you're trying to track more than just player input is going to get exponentially more complicate with every new thing you try and track)

Another question I have for Unity/C#, when do InvokeRepeating, is the time based on something that will be the same across hardware? Or will it be one of those things where at 120fps it'll fire off the invoke method more often than someone playing it at 30fps in the same amount of time? I'm using InvokeRepeating on my spawner to spawn bombs for my conveyor belt boss. Wondering if this is problematic and I should tie it to a time.deltatime thing instead?

I think both invoke delay (and the coroutine alternative yield for new n seconds) are both internally using Time anyway, which is both a sufficiently big enough number as its baseline (seconds) that any drift between different spec machines isn't going to be that big a deal, and also something ultimately measured via Operating System hardware (as I believe it gets its values from system clock).
I mean, basically any real machine differences is probably going to fall into the realm of 'imperceptible to humans' so I wouldn't sweat it too much.

Bebpo

  • Senior Member
Re: Do any of you code for your jobs?
« Reply #358 on: April 30, 2022, 10:31:19 PM »
Finally googled some stuff on game dev creative block and viola there's a lot of very helpful tips out there because this is not a unique thing.

Best advice I found was get off social media and make a small shitty game in a day or two based on one idea whether it's good or bad, because you can't get good at stuff unless you make some sucky things first and just getting something done is motivating. Gonna try that out to get motivated again.

GreatSageEqualOfHeaven

  • Dumbass Monkey
  • Senior Member
Re: Do any of you code for your jobs?
« Reply #359 on: May 01, 2022, 07:50:35 AM »
Finally googled some stuff on game dev creative block and viola there's a lot of very helpful tips out there because this is not a unique thing.

Best advice I found was get off social media and make a small shitty game in a day or two based on one idea whether it's good or bad, because you can't get good at stuff unless you make some sucky things first and just getting something done is motivating. Gonna try that out to get motivated again.

Yeah, gamejams are fun (and if you wanna do one just go to itch, they have like, 50 a fucking week lol) but I always lose focus on personal projects and either end up just noodling or abandoning them